I'm trying to display values from a database activity that is created within the application itself. The values were originally parsed from XML files and then stored into the DB. I have done a good amount of searching and tried several methods of reaching a solution but I seem to be stuck. If someone could help me it out it would be great!
Q, (I)The values must be displayed in a TextView once an item from a ListView is selected. To do this I have set up an onItemClickListener in the ListView Activity(ListRSSItemsActivity) and an intent to start the new activity, as well as created a corresponding Layout file. I'm more or less familiar with how to get a TextView working. But, I'm unsure of what to be putting in the New Activity(ArticleActivity) file now.
(II) When I click on the item and the new window opens, it displays a blank screen.
I have attached the new activity class and the layout file.
ArticleActivity:
public class ArticleActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.article_view);
String title, description;
title=this.getIntent().getStringExtra("TAG_TITLE");
description=this.getIntent().getStringExtra("TAG_DESCRIPTION");
}
}
article_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Article Title -->
<TextView android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:paddingBottom="8dp"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#dc6800"/>
<!-- Article Content -->
<TextView android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#acacac"
android:layout_below="#id/title"/>
</RelativeLayout>
ListRSSItemsActivity:
public class ListRSSItemsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Array list for list view
ArrayList<HashMap<String, String>> rssItemList = new ArrayList<HashMap<String,String>>();
RSSParser rssParser = new RSSParser();
List<RSSItem> rssItems = new ArrayList<RSSItem>();
RSSFeed rssFeed;
public static String TAG_TITLE = "title";
private static String TAG_LINK = "link";
private static String TAG_DESCRIPTION = "description";
private static String TAG_PUBDATE = "pub_date";
private static String TAG_GUID = "guid"; // not used
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.rss_item_list);
// get intent data
Intent i = getIntent();
// SQLite Row id
Integer site_id = Integer.parseInt(i.getStringExtra("id"));
// Getting Single website from SQLite
RSSDatabaseHandler rssDB = new RSSDatabaseHandler(getApplicationContext());
WebSite site = rssDB.getSite(site_id);
String rss_link = site.getRSSLink();
/**
* Calling a backgroung thread will loads recent articles of a website
* #param rss url of website
* */
new loadRSSFeedItems().execute(rss_link);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listview
View v = (View)view.getParent();
TextView tv = (TextView)v.findViewById(R.id.title);
String title = tv.getText().toString();
String description = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
Intent ia = new Intent(getApplicationContext(), ArticleActivity.class);
ia.putExtra("TAG_TITLE", title);
ia.putExtra("TAG_DESCRIPTION", description);
startActivity(ia);
}
});
}
/**
* Background Async Task to get RSS Feed Items data from URL
* */
class loadRSSFeedItems extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(
ListRSSItemsActivity.this);
pDialog.setMessage("Loading recent articles...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting all recent articles and showing them in listview
* */
#Override
protected String doInBackground(String... args) {
// rss link url
String rss_url = args[0];
// list of rss items
// using GET method to obtain rssfeeditems. NOTICE: only from RSS_URL here!
rssItems = rssParser.getRSSFeedItems(rss_url);
// looping through each item
for(RSSItem item : rssItems){
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TITLE, item.getTitle());
map.put(TAG_LINK, item.getLink());
map.put(TAG_PUBDATE, item.getPubDate());
String description = item.getDescription();
// taking only 200 chars from description
if(description.length() > 100){
description = description.substring(0, 97) + "..";
}
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
rssItemList.add(map);
}
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed items into listview
* */
ListAdapter adapter = new SimpleAdapter(
ListRSSItemsActivity.this,
rssItemList, R.layout.rss_item_list_row,
new String[] { TAG_LINK, TAG_TITLE, TAG_PUBDATE, TAG_DESCRIPTION },
new int[] { R.id.page_url, R.id.title, R.id.pub_date, R.id.link });
// updating listview
setListAdapter(adapter);
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String args) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
}
Database Activity:
public class RSSDatabaseHandler extends SQLiteOpenHelper{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "rssReader";
// Contacts table name
private static final String TABLE_RSS = "websites";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_LINK = "link";
private static final String KEY_RSS_LINK = "rss_link";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_PUBDATE = "pub_date";
public RSSDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_RSS_TABLE = "CREATE TABLE " + TABLE_RSS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT," + KEY_LINK
+ " TEXT," + KEY_RSS_LINK + " TEXT," + KEY_DESCRIPTION
+ " TEXT," + KEY_PUBDATE + " TEXT" + ")";
db.execSQL(CREATE_RSS_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_RSS);
// Create tables again
onCreate(db);
}
/**
* Adding a new website in websites table Function will check if a site
* already existed in database. If existed will update the old one else
* creates a new row
* */
public void addSite(WebSite site) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, site.getTitle()); // site title
values.put(KEY_LINK, site.getLink()); // site url
values.put(KEY_RSS_LINK, site.getRSSLink()); // rss link url
values.put(KEY_DESCRIPTION, site.getDescription()); // site description
values.put(KEY_PUBDATE, site.getPubDate());
// Check if row already existed in database
if (!isSiteExists(db, site.getRSSLink())) {
// site not existed, create a new row
db.insert(TABLE_RSS, null, values);
db.close();
} else {
// site already existed update the row
updateSite(site);
db.close();
}
}
/**
* Reading all rows from database
* */
public List<WebSite> getAllSites() {
List<WebSite> siteList = new ArrayList<WebSite>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RSS
+ " ORDER BY id DESC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
WebSite site = new WebSite();
site.setId(Integer.parseInt(cursor.getString(0)));
site.setTitle(cursor.getString(1));
site.setLink(cursor.getString(2));
site.setRSSLink(cursor.getString(3));
site.setDescription(cursor.getString(4));
site.setPubDate(cursor.getString(5));
// Adding contact to list
siteList.add(site);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return siteList;
}
/**
* Updating a single row row will be identified by rss link
* */
public int updateSite(WebSite site) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, site.getTitle());
values.put(KEY_LINK, site.getLink());
values.put(KEY_RSS_LINK, site.getRSSLink());
values.put(KEY_DESCRIPTION, site.getDescription());
values.put(KEY_PUBDATE, site.getPubDate());
// updating row return
int update = db.update(TABLE_RSS, values, KEY_RSS_LINK + " = ?",
new String[] { String.valueOf(site.getRSSLink()) });
db.close();
return update;
}
/**
* Reading a row (website) row is identified by row id
* */
// Declaring
public WebSite getSite(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RSS, new String[] { KEY_ID, KEY_TITLE,
KEY_LINK, KEY_RSS_LINK, KEY_DESCRIPTION, KEY_PUBDATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
WebSite site = new WebSite(cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
site.setId(Integer.parseInt(cursor.getString(0)));
site.setTitle(cursor.getString(1));
site.setLink(cursor.getString(2));
site.setRSSLink(cursor.getString(3));
site.setDescription(cursor.getString(4));
site.setPubDate(cursor.getString(5));
cursor.close();
db.close();
return site;
}
/**
* Deleting single row
* */
public void deleteSite(WebSite site) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RSS, KEY_ID + " = ?",
new String[] { String.valueOf(site.getId())});
db.close();
}
/**
* Checking whether a site is already existed check is done by matching rss
* link
* */
public boolean isSiteExists(SQLiteDatabase db, String rss_link) {
Cursor cursor = db.rawQuery("SELECT 1 FROM " + TABLE_RSS
+ " WHERE rss_link = '" + rss_link + "'", new String[] {});
boolean exists = (cursor.getCount() > 0);
return exists;
}
}
Remove these lines:
ia.putExtra("TAG_TITLE", "title");
ia.putExtra("TAG_DESCRIPTION", "description");
and Replace with below:
ia.putExtra("TAG_TITLE", title);
ia.putExtra("TAG_DESCRIPTION", description);
Change the code in ArticleActivity:
Remove Below Code:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString(TAG_TITLE, "title");
Replace with below code:
String title,description;
TextView txtTitle,txtDesc;
txtTitle=(TextView)findViewById(R.id.title);
txtDesc=(TextView)findViewById(R.id.description);
title=this.getIntent().getStringExtra("TAG_TITLE");
description=this.getIntent().getStringExtra("TAG_DESCRIPTON");
txtTitle.setText(title);
txtDesc.setText(description);
}
And set these values in your respected TextView or anywhere else as per your need.
try the following
create a shared preference
put the appropirate data in the shared preference in the list item select listener
In the oncreate of activity (in which u want to data to be shown) ,read the data from shared preference and show the data as per u want.
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();
}
});
I want to retrieve data from the database so that only those data should be listview which will work on the true condition.
I have added two spinners in the XML file. One spinner contains the default values stored in java file for getting options of blood group and second contains city names.
I want that if a user selects BloodGroup as O+ve from spinner and City as Gurgaon and clicks on search button then the details of the person will be shown in the listview that follows both spinner queries.
The following is a working example of how you can apply the SelectedItem from two spinners and then by clicking a Search button display only rows that contain both items are then listed (if any).
The examples are based upon the scenario you provide. That is there is a specific list of Cities and BloodGroups that can be selected via the Spinners. The records table includes columns for both plus two columns _id and name. The test database is populated with 100 random names, cities and bloodgroups.
The layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blood Bank" />
<Spinner
android:id="#+id/select_bloodgroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
<Spinner
android:id="#+id/select_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Spinner>
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"/>
<ListView
android:id="#+id/records_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
The DatabaseHelper DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "bloodbank";
public static final int DBVERSION = 1;
public static final String TB_RECORDS = "records";
public static final String COl_RECORDS_ID = BaseColumns._ID;
public static final String COL_RECORDS_NAME = "_name";
public static final String COL_RECORDS_BLOODGROUP = "_blood_group";
public static final String COL_RECORDS_CITY = "_city";
SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context,DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crtrecords = "CREATE TABLE IF NOT EXISTS " +
TB_RECORDS + "(" +
COl_RECORDS_ID + " INTEGER PRIMARY KEY," +
COL_RECORDS_NAME + " TEXT," +
COL_RECORDS_CITY + " TEXT, " +
COL_RECORDS_BLOODGROUP + " TEXT" +
")";
db.execSQL(crtrecords);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public long addRecord(String name, String city, String bloodgroup) {
ContentValues cv = new ContentValues();
cv.put(COL_RECORDS_NAME,name);
cv.put(COL_RECORDS_CITY,city);
cv.put(COL_RECORDS_BLOODGROUP,bloodgroup);
return mDB.insert(TB_RECORDS,null,cv);
}
public Cursor getrecords(String city, String bloodgroup) {
ArrayList<String> baseargs = new ArrayList<>();
String whereclause = null;
if (city != null && city.length() > 0) {
whereclause = COL_RECORDS_CITY + "=?";
baseargs.add(city);
}
if (bloodgroup != null && bloodgroup.length() > 0) {
if (whereclause != null && whereclause.length() > 0) {
whereclause = whereclause + " AND ";
} else whereclause = "";
whereclause = whereclause + COL_RECORDS_BLOODGROUP + "=?";
baseargs.add(bloodgroup);
}
String[] whereargs = null;
if (baseargs.size() > 0) {
whereargs = new String[baseargs.size()];
for (int i =0; i < baseargs.size();i++) {
whereargs[i] = baseargs.get(i);
}
}
return mDB.query(TB_RECORDS,null,whereclause,whereargs,null,null,COL_RECORDS_NAME);
}
}
The invoking activity MainActivity.java :-
public class MainActivity extends AppCompatActivity {
//Specific Blood groups
public static final String[] BLOODGROUPS = new String[]{
"A+","A-","B+","B-","0+","0-","AB+","AB-"
};
//Specific Cities
public static final String[] CITIES = new String[]{
"London","Paris","New York","Montreal","Gurgaon"
};
// Some names for auto generation of test data
static final String[] peoples_names = new String[]{
"Fred","Mary","Bert","Anne","James","Susan","Tom","Theresa",
"Cherles","Corrine","David","Diana","Edward","Esmerelda",
"George","Gorgina","Harrold","Heather"
};
TextView mTitle;
Spinner mBloodGroups, mCities;
Button mSearch;
DBHelper mDBHlpr;
ArrayAdapter<String> mCitiesAdapter, mBloodGroupsAdapater;
ListView mRecordsList;
SimpleCursorAdapter mSCA;
String mCurrentCities = "", mCurrentBloodGroups = "";
Cursor mCsr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = this.findViewById(R.id.title);
mBloodGroups = this.findViewById(R.id.select_bloodgroup);
mCities = this.findViewById(R.id.select_city);
mSearch = this.findViewById(R.id.search);
mRecordsList = this.findViewById(R.id.records_list);
mCurrentCities = "";
mCurrentBloodGroups = "";
// Add some test data
mDBHlpr = new DBHelper(this);
if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TB_RECORDS) < 1) {
Random rnd = new Random();
rnd.setSeed(System.currentTimeMillis());
for (int i = 0; i < 100; i++) {
mDBHlpr.addRecord(
peoples_names[rnd.nextInt(peoples_names.length)],
CITIES[rnd.nextInt(CITIES.length)],
BLOODGROUPS[rnd.nextInt(BLOODGROUPS.length)]
);
}
}
//Setup City Spinner
mCitiesAdapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,CITIES);
mCities.setAdapter(mCitiesAdapter);
//Setup Bloodgroups Spinner
mBloodGroupsAdapater = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,BLOODGROUPS);
mBloodGroups.setAdapter(mBloodGroupsAdapater);
// Add Search Buitton Click Listener
mSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentCities = mCities.getSelectedItem().toString();
mCurrentBloodGroups = mBloodGroups.getSelectedItem().toString();
refreshList();
}
});
// Initial List (All)
refreshList();
}
//Setup or refresh the ListView
private void refreshList() {
// Grab the data
mCsr = mDBHlpr.getrecords(mCurrentCities,mCurrentBloodGroups);
// If first time then setup the Cursor Adapter
if (mSCA == null) {
mSCA = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2,
mCsr,
new String[]{DBHelper.COL_RECORDS_NAME,DBHelper.COL_RECORDS_CITY},
new int[]{android.R.id.text1, android.R.id.text2},
0
);
mRecordsList.setAdapter(mSCA);
}
// If not first time then swap the cursor
else {
mSCA.swapCursor(mCsr);
}
}
}
Result
Initially the following is displayed (as the data is random generated it may differ although there will be 100 item listed) :-
After Selecting City Gurgaon :- (note results will likely differ due to random data) :-
After Selecting Bloodgroup A- :- (again results will likely differ) :-
Note this example works, the intention is that you learn from the supplied code and do YOUR research, if you have subsequent questions then you should ask them as separate and distinct questions on Stack Overflow.
I have a table in DataBase, and I want to make a table.
Now it makes no sense that I will do a lot of CheckBox and show you only some of them according to the information in the table. I heard about the listview
But how do I do listview of checkbox I found an example of listview on the Internet and when I tried to insert large information, only half the information came in, so I was told to do adapter.
Do you have an example of how to do this?
It DatabaseHandler:
package budgetreport.com.budgetreport;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "Records_Item Purcashes";
// Contacts table name
private static final String TABLE_RECORDS = "Records";
// Contacts Table Columns names
private static final String KEY_ID = "ID";
private static final String KEY_PRICE = "Price";
private static final String KEY_ITEM = "Item";
private static final String KEY_DETAILS = "Details";
private static final String KEY_DATE = "Date";
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_RECORDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_PRICE + " INTEGER," + KEY_ITEM + " TEXT,"
+ KEY_DETAILS + " TEXT, " + KEY_DATE + " 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_RECORDS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addRecord(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId()); // Contact Name
values.put(KEY_PRICE, record.getPrice()); // Contact Name
values.put(KEY_ITEM, record.getItem()); // Contact Name
values.put(KEY_DETAILS, record.getDetails()); // Contact Name
values.put(KEY_DATE, record.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_RECORDS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Record getRecord(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RECORDS, new String[] { KEY_ID, KEY_PRICE,
KEY_ITEM, KEY_DETAILS, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Record record = new Record(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return record;
}
// Getting All Contacts
public List<Record> getAllContacts() {
List<Record> contactList = new ArrayList<Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Record record = new Record();
record.setId(Integer.parseInt(cursor.getString(0)));
record.setPrice(Integer.parseInt(cursor.getString(1)));
record.setItem(cursor.getString(2));
record.setDetails(cursor.getString(3));
record.setDate(cursor.getString(4));
// Adding contact to list
contactList.add(record);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Getting contacts Count
public int getRecordsCount() {
String countQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateContact(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId());
values.put(KEY_PRICE, record.getPrice());
values.put(KEY_DETAILS, record.getDetails());
values.put(KEY_DATE, record.getDate());
// updating row
return db.update(TABLE_RECORDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(record.getPrice()) });
}
// Deleting single contact
public void deleteContact(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECORDS, KEY_ID + " = ?",new String[]
{String.valueOf(record.getPrice()) });
db.close();
}
}
Deletion of checked Items as per I want to erase the lines I have marked.
This is relatively simple to progress to.
It involves
- a) adding a method to the database helper to delete according to id.
- b) (i)amend the onClick listener to invoke the delete method (simple loop) and to then (ii)update the listview (after the loop).
However, the original custom adapter has some flaws in that the original cursor is retained via mCsr and no consideration was given to the number of checkboxes being changed when the Cursor is changed (swapped).
As such the adapter has had references to mCsr removed and replaced by the Cursor passed or via calling the getCursor method. Also the swapCursor() method has been overidden to adjust the number of elements of and re-initialise the elemnets (set to false), of mCheckBoxes.
a) The new deleteRecord method :-
public boolean deleteRecord(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return (db.delete(TABLE_RECORDS,KEY_ID + "=?",new String[]{Long.toString(id)})> 0);
}
b)(i) onCLickListener amendments (note includes grouping all deletes into a single transaction) :-
// <<<<< DO IT BUTTON HANDLER i.e. get list of ID's for checked items
mDoItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the ID's for the checked Items
mCheckedIdList = mMCA.getCheckedRecordIdList();
Toast.makeText(mContext,"You have " + mCheckedIdList.length + " Items checked.",Toast.LENGTH_SHORT).show();
//<<<< to delete
SQLiteDatabase db = mDBHandler.getWritableDatabase();
db.beginTransaction();
for (long id: mCheckedIdList) {
mDBHandler.deleteRecord(id);
}
db.setTransactionSuccessful();
db.endTransaction();
refreshListView();
}
});
b(ii) Update the Listview (new method in the Activity) :-
private void refreshListView() {
mCsr = mDBHandler.getAllRecords();
mMCA.swapCursor(mCsr);
}
Notes
this is added as a method to the activity.
mMCA.notifyDatasetChanged(); is an alternative (I personally prefer `swapCursor1 as it's more decsriptive).
The modified Custom Cursor Adapter should be :-
public class MyCustomCursorAdapter extends CursorAdapter {
private Context mContext;
private String[] mColumns;
private int[] mViews;
private int mLayout;
private boolean[] mCheckBoxStates;
private int mCheckBoxView;
// Constructor for the Custom Cursor Adapter
MyCustomCursorAdapter(Context context, int layout, Cursor csr, String[] from_columns, int[] to_views, int checkbox_view) {
super(context,csr, false);
mContext = context;
mLayout = layout;
mColumns = from_columns;
mViews = to_views;
mCheckBoxView = checkbox_view;
}
#Override
// Inflate the layout we are going to use (as passed via 2nd parameter)
public View newView(Context context, Cursor csr, ViewGroup parent) {
// Initialise an int array for the checkboxes (all will be 0)
mCheckBoxStates = new boolean[csr.getCount()];
return LayoutInflater.from(context).inflate(mLayout,parent,false);
}
#Override
// Tie the from_columns to the display views
public void bindView(View view, Context context, Cursor csr) {
final Cursor fcsr = csr;
// Place the data from the cursor into the respective View (TextView)
for (int i = 0; i < mColumns.length; i++) {
((TextView) view.findViewById(mViews[i])).setText(csr.getString(csr.getColumnIndex(mColumns[i])));
}
// Set the checkbox (note should be false, unless otherwise changed)
CheckBox currentCheckBox = (CheckBox) view.findViewById(mCheckBoxView);
currentCheckBox.setChecked(mCheckBoxStates[csr.getPosition()]);
currentCheckBox.setTag(new Long(csr.getLong(csr.getColumnIndex(DatabaseHandler.KEY_ID))));
//
currentCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
final int position = fcsr.getPosition();
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Store the checkbox status
mCheckBoxStates[position] = ((CheckBox) buttonView).isChecked();
int restore_cursor_position = fcsr.getPosition();
//Move the Cursor to the respective row
//NOTE! 1st position in Lisview is 1 but equates to cursor row 0 etc hence -1
fcsr.moveToPosition(position);
Toast.makeText(mContext,
"You Changed the CheckBox for row " +
Integer.toString(position + 1) +
" Item is " +
fcsr.getString(fcsr.getColumnIndex(DatabaseHandler.KEY_ITEM))
,
Toast.LENGTH_SHORT
).show();
//restore the Cursor's position
fcsr.moveToPosition(restore_cursor_position);
}
});
}
// get the list of items (the ID's as long) that have been checked.
public long[] getCheckedRecordIdList() {
Cursor csr = this.getCursor();
// using ArrayList as we can add as we don't yet know how many
ArrayList<Long> rva = new ArrayList<>();
// Just in case save the current position of the Cursor
int restore_cursor_position = csr.getPosition();
// Loop through the checkbox states
for (int i=0; i < mCheckBoxStates.length; i++) {
// If the checkbox reflected as being checked then handle, else ignore it
if (mCheckBoxStates[i]) {
// Move to the respective cursor row
csr.moveToPosition(i);
// get the respective ID and store in the arraylist
rva.add(csr.getLong(csr.getColumnIndex(DatabaseHandler.KEY_ID)));
}
}
// Done with the Cursor so re-position it
csr.moveToPosition(restore_cursor_position);
// Create the long array to be returned
long[] rv = new long[rva.size()];
// Populate the long array with the id's from the arraylist
for (int i=0; i < rva.size(); i++) {
rv[i] = rva.get(i);
}
// return the long[]
return rv;
}
#Override
public Cursor swapCursor(Cursor csr) {
mCheckBoxStates = new boolean[csr.getCount()];
for (int i=0; i < mCheckBoxStates.length; i++) {
mCheckBoxStates[i] = false;
}
return super.swapCursor(csr);
}
}
here's an example based upon you code.
1) The Activity's layout (i.e a ListView with an id of lv001) as file activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mjt.budgetreport.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="10dp"
/>
<ListView
android:id="#+id/lv001"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
2) A layout for each row (Item in ListView terminology) as file listviewitem_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/record_price"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_item"
android:layout_width="0dp"
android:layout_weight="10"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_details"
android:layout_width="0dp"
android:layout_weight="20"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_date"
android:layout_width="0dp"
android:layout_weight="10"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<CheckBox
android:id="#+id/record_checkbox"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
</LinearLayout>
Note! the inclusion of a CheckBox, as well as TextViews for all columns.
3) To simplify matters I used this as DatabaseHandler.java :-
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 4;
// Database Name
public static final String DATABASE_NAME = "Records_Item Purcashes";
// Contacts table name
public static final String TABLE_RECORDS = "Records";
// Contacts Table Columns names
public static final String KEY_ID = "_id";
public static final String KEY_PRICE = "Price";
public static final String KEY_ITEM = "Item";
public static final String KEY_DETAILS = "Details";
public static final String KEY_DATE = "Date";
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_RECORDS +
"(" +
KEY_ID + " INTEGER PRIMARY KEY," +
KEY_PRICE + " INTEGER," +
KEY_ITEM + " TEXT," +
KEY_DETAILS + " TEXT, " +
KEY_DATE + " 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_RECORDS);
// Create tables again
onCreate(db);
}
public void insertRecord(int price, String item, String details, String date) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRICE,price);
cv.put(KEY_ITEM,item);
cv.put(KEY_DETAILS,details);
cv.put(KEY_DATE,date);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECORDS,null,cv);
}
public Cursor getAllRecords() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_RECORDS,null,null,null,null,null,null);
}
/*
// Adding new contact
public void addRecord(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId()); // Contact Name
values.put(KEY_PRICE, record.getPrice()); // Contact Name
values.put(KEY_ITEM, record.getItem()); // Contact Name
values.put(KEY_DETAILS, record.getDetails()); // Contact Name
values.put(KEY_DATE, record.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_RECORDS, null, values);
db.close(); // Closing database connection
}
*/
/*
// Getting single contact
public AlphabeticIndex.Record getRecord(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RECORDS, new String[] { KEY_ID, KEY_PRICE,
KEY_ITEM, KEY_DETAILS, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
AlphabeticIndex.Record record = new AlphabeticIndex.Record(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return record;
}
*/
/*
// Getting All Contacts
public List<AlphabeticIndex.Record> getAllContacts() {
List<AlphabeticIndex.Record> contactList = new ArrayList<AlphabeticIndex.Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AlphabeticIndex.Record record = new AlphabeticIndex.Record();
record.setId(Integer.parseInt(cursor.getString(0)));
record.setPrice(Integer.parseInt(cursor.getString(1)));
record.setItem(cursor.getString(2));
record.setDetails(cursor.getString(3));
record.setDate(cursor.getString(4));
// Adding contact to list
contactList.add(record);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
*/
/*
// Getting contacts Count
public int getRecordsCount() {
String countQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// cursor.close();
// return count
return cursor.getCount();
}
*/
/*
// Updating single contact
public int updateContact(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId());
values.put(KEY_PRICE, record.getPrice());
values.put(KEY_DETAILS, record.getDetails());
values.put(KEY_DATE, record.getDate());
// updating row
return db.update(TABLE_RECORDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(record.getPrice()) });
}
*/
/*
// Deleting single contact
public void deleteContact(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECORDS, KEY_ID + " = ?",new String[]
{String.valueOf(record.getPrice()) });
db.close();
}
*/
}
Notes about Changes to DatabaseHandler.java
The rowid alias has been changed from ID to _id, this is because CursorAdapter's need a column named _id and that column should be an alias for for the rowid (not going into technicalities here).
Instead of using a Record class I've commented out your code that uses this class, for my convenience.
I've changed TABLE and COLUMN names definitions to public, so they can be accessed elsewhere.
I've added two new methods insertRecord and getAllRecords:-
insertRecord just to add some data for testing/example
getAllRecords retrieves all rows as a Cursor, as opposed to an array.
NOTE! The database is not closed, this would result in an exception because a Cursor needs access to the database (opening and closing a database can be detrimental anyway).
4) The Activity itself (just displays the ListView after adding some data for the first run) as file MainActivity.java :-
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) this.findViewById(R.id.lv001); // Get the ListView from it's id
mDBHandler = new DatabaseHandler(this); // Get an instance of the Database Handler
// Add some data but only if there is no data
if (DatabaseUtils.queryNumEntries(mDBHandler.getWritableDatabase(),DatabaseHandler.TABLE_RECORDS) < 1) {
mDBHandler.insertRecord(100,"Rock","A large stone.","31/12/2017");
mDBHandler.insertRecord(50,"Boulder","A Rock.","31/12/2018");
mDBHandler.insertRecord(322,"Soil","Loose earth.","31/7/2015");
mDBHandler.insertRecord(237,"Stone","A small rock.","31/8/2014");
mDBHandler.insertRecord(32,"Pebble","A small smooth stone.","11/12/2017");
}
// get all rows into a Cursor
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_PRICE,
DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_DETAILS,
DatabaseHandler.KEY_DATE
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.record_price,
R.id.record_item,
R.id.record_details,
R.id.record_date
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
}
}
Result :-
Notes
This doesn't go into handling the checkboxes, this would likely need a CustomAdapter. There's plenty of tutorials for that e.g. how do i create a custom cursor adapter for a listview for use with images and text?.
Edit Amended to Include CheckBox handling
1) The Activity's layout activity_main.xml - Added a Button for getting Checked Items :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mjt.budgetreport.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="10dp"
/>
<Button
android:id="#+id/doitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DO ALL CHECKED ROWS"
/>
<ListView
android:id="#+id/lv001"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
2) The Custom Cursor Adapter MyCustomCursorAdapter.java
Signature similar to SimpleCursorAdapter BUT with an extra parameter for the id of the CheckBox.
Includes method getCheckedRecordIdList, which will return a list of Id's that have been checked.
Issues a Toast when a checkbox is checked or unchecked which displays the item, as in the ListView's Item # (not the Item in the table), clicked and the Item clicked (as in the Item value from the table).
:-
public class MyCustomCursorAdapter extends CursorAdapter {
private Context mContext;
private Cursor mCsr;
private String[] mColumns;
private int[] mViews;
private int mLayout;
private boolean[] mCheckBoxStates;
private int mCheckBoxView;
// Constructor for the Custom Cursor Adapter
MyCustomCursorAdapter(Context context, int layout, Cursor csr, String[] from_columns, int[] to_views, int checkbox_view) {
super(context,csr, false);
mContext = context;
mLayout = layout;
mCsr = csr;
mColumns = from_columns;
mViews = to_views;
mCheckBoxView = checkbox_view;
}
#Override
// Inflate the layout we are going to use (as passed via 2nd parameter)
public View newView(Context context, Cursor csr, ViewGroup parent) {
// Initialise an int array for the checkboxes (all will be 0)
mCheckBoxStates = new boolean[csr.getCount()];
return LayoutInflater.from(context).inflate(mLayout,parent,false);
}
#Override
// Tie the from_columns to the display views
public void bindView(View view, Context context, Cursor csr) {
// Place the data from the cursor into the respective View (TextView)
for (int i = 0; i < mColumns.length; i++) {
((TextView) view.findViewById(mViews[i])).setText(csr.getString(csr.getColumnIndex(mColumns[i])));
}
// Set the checkbox (note should be false, unless otherwise changed)
CheckBox currentCheckBox = (CheckBox) view.findViewById(mCheckBoxView);
currentCheckBox.setChecked(mCheckBoxStates[mCsr.getPosition()]);
currentCheckBox.setTag(new Long(mCsr.getLong(mCsr.getColumnIndex(DatabaseHandler.KEY_ID))));
//
currentCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
final int position = mCsr.getPosition();
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Store the checkbox status
mCheckBoxStates[position] = ((CheckBox) buttonView).isChecked();
int restore_cursor_position = mCsr.getPosition();
//Move the Cursor to the respective row
//NOTE! 1st position in Lisview is 1 but equates to cursor row 0 etc hence -1
mCsr.moveToPosition(position);
Toast.makeText(mContext,
"You Changed the CheckBox for row " +
Integer.toString(position + 1) +
" Item is " +
mCsr.getString(mCsr.getColumnIndex(DatabaseHandler.KEY_ITEM))
,
Toast.LENGTH_SHORT
).show();
//restore the Cursor's position
mCsr.moveToPosition(restore_cursor_position);
}
});
}
// get the list of items (the ID's as long) that have been checked.
public long[] getCheckedRecordIdList() {
// using ArrayList as we can add as we don't yet know how many
ArrayList<Long> rva = new ArrayList<>();
// Just in case save the current position of the Cursor
int restore_cursor_position = mCsr.getPosition();
// Loop through the checkbox states
for (int i=0; i < mCheckBoxStates.length; i++) {
// If the checkbox reflected as being checked then handle, else ignore it
if (mCheckBoxStates[i]) {
// Move to the respective cursor row
mCsr.moveToPosition(i);
// get the respective ID and store in the arraylist
rva.add(mCsr.getLong(mCsr.getColumnIndex(DatabaseHandler.KEY_ID)));
}
}
// Done with the Cursor so re-position it
mCsr.moveToPosition(restore_cursor_position);
// Create the long array to be returned
long[] rv = new long[rva.size()];
// Populate the long array with the id's from the arraylist
for (int i=0; i < rva.size(); i++) {
rv[i] = rva.get(i);
}
// return the long[]
return rv;
}
}
3) The amended MainActivity to use the Custom Adapter and to get the list of checked Records (displays number selected via Toast) - MainActivity.java
Changed/Added Lines/Methods are marked with <<<<<.
:-
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
MyCustomCursorAdapter mMCA; // <<<<<
Cursor mCsr;
Button mDoItButton;
Context mContext; //<<<<<
long[] mCheckedIdList; //<<<<<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) this.findViewById(R.id.lv001); // Get the ListView from it's id
mDoItButton = (Button) this.findViewById(R.id.doitbutton); //<<<<<
mDBHandler = new DatabaseHandler(this); // Get an instance of the Database Handler
// Add some data but only if there is no data
if (DatabaseUtils.queryNumEntries(mDBHandler.getWritableDatabase(),DatabaseHandler.TABLE_RECORDS) < 1) {
mDBHandler.insertRecord(100,"Rock","A large stone.","31/12/2017");
mDBHandler.insertRecord(50,"Boulder","A Rock.","31/12/2018");
mDBHandler.insertRecord(322,"Soil","Loose earth.","31/7/2015");
mDBHandler.insertRecord(237,"Stone","A small rock.","31/8/2014");
mDBHandler.insertRecord(32,"Pebble","A small smooth stone.","11/12/2017");
}
mDBHandler.increasePrice(1,213);
// get all rows into a Cursor
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_ID,
DatabaseHandler.KEY_PRICE,
DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_DETAILS,
DatabaseHandler.KEY_DATE
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.record_id,
R.id.record_price,
R.id.record_item,
R.id.record_details,
R.id.record_date
};
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mSCA = new SimpleCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Tie the adapter to the Listview
mListView.setAdapter(mSCA);
// <<<<<< Alternate Custom Cursor Adapter
mMCA = new MyCustomCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
R.id.record_checkbox //<<<<<< id of the checkbox
);
// Hijack the Listview
mListView.setAdapter(mMCA); //<<<<<<
// <<<<< DO IT BUTTON HANDLER i.e. get list of ID's for checked items
mDoItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the ID's for the checked Items
mCheckedIdList = mMCA.getCheckedRecordIdList();
Toast.makeText(mContext,"You have " + mCheckedIdList.length + " Items checked.",Toast.LENGTH_SHORT).show();
}
});
}
}
Note! you wouldn't typically have two adapters, but I left the SimpleCursorAdapter in for comparison.
Note! be a little patient, as if you click too much too soon you may get consfused.
Note! See other answer for deleting checked items.
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