Alert dialog delete a row on ListView Item click - android

Good Day Guys..Need some help here..i got troubled from deleting the selected row in my list view..i want to use an alert dialog for confirmation to delete the selected row..and to edit also..i am a beginner and i have tried searching for answers to this problem and also tried relating it to other problems but i still didn't get it...
My DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper implements Filterable{
// private static final String COLUMN_NAME="ageing_column";
private static final String DATABASE_NAME=" EXPIRATIONMONITORING.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ContractClass.NewInfo.TABLE_NAME+"("+ ContractClass.NewInfo.ITEM_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+ContractClass.NewInfo.DESCRIPTION+" TEXT, "+
ContractClass.NewInfo.CATEGORY+" TEXT,"+ ContractClass.NewInfo.MONTHONE+" TEXT, "+ ContractClass.NewInfo.REMIND_AT+" TEXT, "+ ContractClass.NewInfo.QTY+" TEXT, "+
ContractClass.NewInfo.LOCATION+" TEXT );";
private SQLiteDatabase sqLiteDatabase;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//this.context1=context;
Log.e("DATABASE OPERATIONS", "Database created / opened....");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created....");
}
public void addInformations(String description, String category, String monthOne,String quantity,String remind, String location, SQLiteDatabase db)
{
ContentValues contentValues=new ContentValues();
contentValues.put(ContractClass.NewInfo.LOCATION,location);
contentValues.put(ContractClass.NewInfo.DESCRIPTION,description);
contentValues.put(ContractClass.NewInfo.CATEGORY,category);
contentValues.put(ContractClass.NewInfo.MONTHONE,monthOne);
contentValues.put(ContractClass.NewInfo.REMIND_AT,remind);
contentValues.put(ContractClass.NewInfo.QTY,quantity);
db.insert(ContractClass.NewInfo.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted");
db.close();
}
public Cursor getInformations(SQLiteDatabase db)
{
Cursor cursor;
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
cursor=db.query(ContractClass.NewInfo.TABLE_NAME, projections, null, null, null, null, null);
return cursor;
}
public Cursor getContact(String location,SQLiteDatabase sqLiteDatabase)
{
String[] projections ={ContractClass.NewInfo.DESCRIPTION,ContractClass.NewInfo.CATEGORY,ContractClass.NewInfo.MONTHONE, ContractClass.NewInfo.QTY, ContractClass.NewInfo.REMIND_AT,ContractClass.NewInfo.LOCATION};
String selection = ContractClass.NewInfo.LOCATION+" LIKE? ";
String [] sargs={location};
Cursor cursor=sqLiteDatabase.query(ContractClass.NewInfo.TABLE_NAME,projections,selection,sargs,null,null,null);
return cursor;
}
public String[] SelectAllData()
{
try
{
String arrData[]=null;
SQLiteDatabase db;
db=this.getReadableDatabase();
String strSQL=" SELECT "+ ContractClass.NewInfo.LOCATION+" FROM "+ ContractClass.NewInfo.TABLE_NAME;
Cursor cursor =db.rawQuery(strSQL,null);
if(cursor !=null)
{
if(cursor.moveToFirst())
{
arrData=new String[cursor.getCount()];
int i=0;
do
{
arrData[i]=cursor.getString(0);
i++;
}while(cursor.moveToNext());
}
}
cursor.close();
return arrData;
}catch(Exception e){
return null;
}
}
public void delete_byID(int id){
sqLiteDatabase.delete(ContractClass.NewInfo.TABLE_NAME, ContractClass.NewInfo.ITEM_ID + "=" + id, null);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public Filter getFilter() {
return null;
}
}
THis is My MAin Class..
public class ViewListsActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
SQLiteDatabase sqLiteDatabase;
ListDataAdapter listDataAdapter;
ListView listView;
Cursor cursor;
EditText delete_txt;
String deletetxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_lists_activity);
listView = (ListView) findViewById(R.id.search_listView);
listDataAdapter = new
ListDataAdapter(getApplicationContext(),R.layout.row_layout);
databaseHelper = new DatabaseHelper(getApplicationContext());
databaseHelper = new DatabaseHelper(this);
delete_txt = (EditText) findViewById(R.id.delete_text);
sqLiteDatabase = databaseHelper.getReadableDatabase();
cursor = databaseHelper.getInformations(sqLiteDatabase);
listView.setAdapter(listDataAdapter);
if (cursor.moveToFirst()) {
do {
String description, category, month1,remind,qty,location;
description = cursor.getString(0);
category = cursor.getString(1);
month1 = cursor.getString(2);
qty=cursor.getString(3);
remind=cursor.getString(4);
location = cursor.getString(5);
DataProvider dataProvider = new DataProvider(description,
category, month1,qty,remind,location);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemLongClickListener(new
AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View
view, int position, long id) {
return false;
}
});
}
public void ToSearchBtn(View view)
{
Intent intent=new Intent(this,ThirdActivitySearchAllData.class);
startActivity(intent);
}
public void ToAddNewItemBtn(View view)
{
Intent intent=new Intent(this,SecondActivitySaveData.class);
startActivity(intent);
}
}
My List Adapter Class
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler
{
TextView DESCRIPTION,CATEGORY,MONTH1,QTY,REMIND,LOCATION;
}
public void add(Object object)
{
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =convertView;
LayoutHandler layoutHandler;
if(row==null)
{
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler=new LayoutHandler();
layoutHandler.DESCRIPTION= (TextView) row.findViewById(R.id.text_description);
layoutHandler.CATEGORY= (TextView) row.findViewById(R.id.text_category);
layoutHandler.MONTH1= (TextView) row.findViewById(R.id.text_monthOne);
layoutHandler.REMIND= (TextView) row.findViewById(R.id.text_remind);
layoutHandler.QTY= (TextView) row.findViewById(R.id.text_qty);
layoutHandler.LOCATION= (TextView) row.findViewById(R.id.text_location);
row.setTag(layoutHandler);
}else
{
layoutHandler=(LayoutHandler)row.getTag();
}
DataProvider dataProvider= (DataProvider) this.getItem(position);
layoutHandler.DESCRIPTION.setText(dataProvider.getDescription());
layoutHandler.CATEGORY.setText(dataProvider.getCategory());
layoutHandler.MONTH1.setText(dataProvider.getMonthOne());
layoutHandler.REMIND.setText(dataProvider.getRemindAt());
layoutHandler.QTY.setText(dataProvider.getQuantity());
layoutHandler.LOCATION.setText(dataProvider.getLocation());
return row;
}
}

You can use ALERT DIALOG for showing confirmation popup, with YES/NO option both for delete and edit, and based on options selected in ALERT DIALOG you can perform further operations
In the below link you can find the sample code
How do I display an alert dialog on Android?

Related

Delete a particular row from a table in SQLite which has a composite primary key

I have written this code to delete a row from one of the tables in my SQLite Database which has a composite primary key. I have an image button in the RecyclerView after clicking on which this action should take place. But this code is not working for me.
This is my adapter class:
public class adapter_cgpa extends RecyclerView.Adapter<adapter_cgpa.Viewholder> {
ArrayList<POJO> cgpaArrayList;
public adapter_cgpa(ArrayList<POJO> cgpaArrayList) {
this.cgpaArrayList = cgpaArrayList;
}
#NonNull
#Override
public adapter_cgpa.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listitem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_cgpa, parent, false);
return new Viewholder(listitem);
}
#Override
public void onBindViewHolder(#NonNull adapter_cgpa.Viewholder holder, int position) {
POJO cgpa= cgpaArrayList.get(position);
holder.cname.setText(cgpa.getCname());
holder.no_of_sems.setText(cgpa.getNo_of_sems());
holder.cgpa.setText(cgpa.getCgpa());
holder.percentage.setText(cgpa.getPercentage());
holder.schemec.setText(cgpa.getSchemec());
}
#Override
public int getItemCount() {
return cgpaArrayList.size();
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cname, no_of_sems, cgpa, percentage,schemec;
ImageButton btndelete2;
public Viewholder(#NonNull View itemView) {
super(itemView);
cname=(TextView)itemView.findViewById(R.id.name);
no_of_sems=(TextView)itemView.findViewById(R.id.no_of_sem);
cgpa=(TextView)itemView.findViewById(R.id.textView49);
percentage=(TextView)itemView.findViewById(R.id.textView55);
schemec=(TextView)itemView.findViewById(R.id.scheme2);
btndelete2=(ImageButton)itemView.findViewById(R.id.btndelete2);
final String snc = (String) cname.getText();
final String semrc = (String) no_of_sems.getText();
final String schc = (String) schemec.getText();
btndelete2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dbmanager db= new dbmanager(v.getContext());
db.delete2(snc,semrc,schc);
}
});
}
}
}
This is my dbmanager class:
public class dbmanager extends SQLiteOpenHelper {
String sgpa_table="create table Sgpa (sname text, semester text, sgpa text,percent text, schemes text, primary key(sname,semester,schemes))";
String cgpa_table="create table Cgpa (cname text, no_of_sems int, cgpa text, percentage text, schemec text, primary key(cname,no_of_sems,schemec))";
public dbmanager(#Nullable Context context) {
super(context, "Student", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(sgpa_table);
db.execSQL(cgpa_table);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor fetch_data1() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select*FROM Sgpa" ;
Cursor cursor = db.rawQuery(query,null);
return cursor;
}
public Cursor fetch_data2() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select*FROM Cgpa" ;
Cursor cursor = db.rawQuery(query,null);
// if (cursor != null) {
// cursor.moveToFirst();
// }
return cursor;
}
public Cursor delete2(String snc, String semrc, String schc){
SQLiteDatabase db=this.getWritableDatabase();
String query= "delete from Cgpa where (cname= ? and no_of_sems = ? and schemec = ?)";
Cursor cursor = db.rawQuery(query, new String[]{snc,semrc,schc});
return cursor;
}
}
Why do you use rawQuery() to delete rows from a table?
Use delete() like this:
public boolean delete2(String snc, String semrc, String schc){
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete("Cgpa", "cname= ? and no_of_sems = ? and schemec = ?", new String[] {snc, semrc, schc});
return result > 0;
}
The method returns a boolean value: true if any row was deleted or false.

Populating Expandable Listview with SQLite database

I have an SQLite database that has the columns ID, Homework, Classname, date. I also have an expandable listview. My code works and creates an expandable listview however it duplicates the group titles.
The group names are from the classname column, and the child objects are added to the group with the same classname. However the expandable listview takes each classname when I really need it to take each unique classname so that it doesn't duplicate the groups. Here is my expandable listview adapter:
public class ExpandListAdapter extends CursorTreeAdapter {
SQLiteHelper values;
private LayoutInflater mInflator;
Context context;
TextView groupHeader;
public ExpandListAdapter(Cursor cursor, Context context){
super(cursor, context);
this.context = context;
values = new SQLiteHelper(context);
mInflator = LayoutInflater.from(context);
}
#Override
public View newGroupView(Context context, Cursor cursor, boolean isExpanded,
ViewGroup parent){
final View view = mInflator.inflate(R.layout.group_header, parent, false);
return view;
}
public void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded){
groupHeader = (TextView) view.findViewById(R.id.group_name);
if(groupHeader != null){
groupHeader.setText(cursor.getString(cursor.getColumnIndex("class")));
}
}
#Override
public View newChildView(Context context, Cursor cursor,
boolean isLastChild, ViewGroup parent){
final View view = mInflator.inflate(R.layout.row_expandable, parent, false);
return view;
}
#Override
public void bindChildView(View view, final Context context, final Cursor cursor,
boolean isLastChild){
TextView homework = (TextView) view.findViewById(R.id.homeworkDisplay1);
if(homework != null){
homework.setText(cursor.getString(cursor.getColumnIndex(values.KEY_HOMEWORK)));
}
TextView date = (TextView) view.findViewById(R.id.dueDisplay1);
if(date != null){
date.setText(cursor.getString(cursor.getColumnIndex(values.KEY_DATE)));
}
TextView classes = (TextView) view.findViewById(R.id.classDisplay1);
if(classes != null){
classes.setText(cursor.getString(cursor.getColumnIndex(values.KEY_CLASS)));
}
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor){
values.open();
Cursor childCursor = values.fetchChildren(groupCursor.getString(groupCursor.getColumnIndex("class")));
childCursor.moveToFirst();
values.close();
return childCursor;
}
#Override
public void onGroupCollapsed(int groupPosition){
}
#Override
public void onGroupExpanded(int groupPosition){
}
}
and here is my SQLitehelper class:
public class SQLiteHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "homeworkManager";
public static final String TABLE_NAME = "homeworkList";
public static final String KEY_ID = "_id";
public static final String KEY_HOMEWORK = "homework";
public static final String KEY_DATE = "date";
public static final String KEY_CLASS = "class";
private SQLiteDatabase db;
private DblistHelper myHelper;
Cursor DB_Cursor;
Context context;
class DblistHelper extends SQLiteOpenHelper {
public DblistHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "Create table " + TABLE_NAME + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_HOMEWORK + " TEXT ,"
+ KEY_DATE + " TEXT ,"
+ KEY_CLASS + " TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public SQLiteHelper(Context context){
this.context = context;
}
public SQLiteHelper open() throws SQLException{
myHelper = new DblistHelper(context);
db = myHelper.getReadableDatabase();
return this;
}
public void close(){
if(myHelper != null){
myHelper.close();
}
}
public long insertData(String homework, String data, String classes){
ContentValues values = new ContentValues();
values.put(KEY_HOMEWORK, homework);
values.put(KEY_DATE, data);
values.put(KEY_CLASS, classes);
return db.insert(TABLE_NAME, null, values);
}
public Cursor fetchGroup(){
String query = "SELECT * FROM homeworkList";
return db.rawQuery(query, null);
}
public Cursor fetchChildren(String class_name){
String query = "SELECT * FROM homeworkList WHERE class = '" + class_name + "'";
Cursor cursor = db.rawQuery(query, null);
return cursor;
}
public void remove(long id){
String whereClause = "_id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
db.delete(TABLE_NAME, whereClause, whereArgs);
}
}
Thanks in advance :)
Hi there instead of passing the Cursor from this constructor
public ExpandListAdapter(Cursor cursor, Context context){
why not just replace it with a List intended for your ListView
public ExpandListAdapter(Context context, List parent, List child){
so that you wont have to fetch data in every view also to prevent data being duplicated

Updating SQL row with OnItemLongClick doesn't work

Can anybody please have a look at my code and tell me where I am wrong? I don't get errors, unfortunately the row that is long pressed and new value is provided is not being updated unless I specify exact row number. I need to be able to update the row that is clicked. I tried everything and up to today I didn't manage to get any help. I am beginner in Android development.
Here is the code of MyDB:
public class MyDB {
private static final String TABLE_NAME = null;
private static final String KEY_ID = null;
private SQLiteDatabase db;
private final Context context;
private final MyDBhelper dbhelper;
// Initializes MyDBHelper instance
public MyDB(Context c){
context = c;
dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
Constants.DATABASE_VERSION);
}
// Closes the database connection
public void close()
{
db.close();
}
// Initializes a SQLiteDatabase instance using MyDBhelper
public void open() throws SQLiteException
{
try {
db = dbhelper.getWritableDatabase();
} catch(SQLiteException ex) {
Log.v("Open database exception caught", ex.getMessage());
db = dbhelper.getReadableDatabase();
}
}
// updates a diary entry (existing row)
public boolean updateDiaryEntry(String title, long rowId)
{
ContentValues newValue = new ContentValues();
newValue.put(Constants.TITLE_NAME, title);
db.beginTransaction();
db.setTransactionSuccessful();
db.endTransaction();
return db.update(Constants.TABLE_NAME , newValue , Constants.KEY_ID + "= ?" ,
new String[]{ Double.valueOf(rowId).toString() })>0;
}
// Reads the diary entries from database, saves them in a Cursor class and returns it from the method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
}
Here is the code with the dialog, where I should update the row:
class EditListItemDialog extends Dialog implements View.OnClickListener {
MyDB dba;
private View editText;
private DiaryAdapter adapter;
private SQLiteDatabase db;
public EditListItemDialog(Context context) {
super(context);
dba = new MyDB(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
dba.open();
}
private List<String> fragment_monday;
private long rowId;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
long rowId = adapter.getItemId(position); //Will return the clicked item
saveItToDB(rowId);
}
public EditListItemDialog(Context context, DiaryAdapter adapter, int position) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
dba = new MyDB(context);
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
// public void notifyDataSetChanged();
dismiss();
try {
saveItToDB(rowId);
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveItToDB(long rowId) {
dba.open();
dba.updateDiaryEntry(((TextView) editText).getText().toString(), rowId);
dba.close();
((TextView) editText).setText("");
}
}
And here is the Diary Adapter:
public class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(Monday.this, null, position).show();
return true;
}
});
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
i found first problem at your DB class
update this method
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, null, null,
null, null, null, null);
return c;
}
To
public Cursor getdiaries()
{
Cursor c = db.query(Constants.TABLE_NAME, new String[]{Constants.TITLE_NAME ,Constants.CONTENT_NAME}, null,
null, null, null, null);
return c;
}

android sqlite getting distinct name and * amounts

I am trying to get a list of names with total amounts from a sqlite db.
It is working in a way that shows a list of all the transactions with the
correct combined total. I also have a table in the same db that has usernames
& phone numbers, but I don't think that would be too useful for this activity.
Also, how do I use the onListItemClick to send the next activity something
that I can use to pull only names from the User the person selected? The ID
is being sent, but I don't know how to use it.
ie:
trans table:
Justin 25
Justin 25
Justin 25
Sophia 80
Hoped results:
Justin 75
Sophia 80
Actual results:
Justin 75
Justin 75
Justin 75
Sophia 80
ListActivity that populates the list (with cursor and TextView link)
public class Totals extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
UserHelper uhelp;
Cursor umodel = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_person);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Totals.this, Detail.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Totals.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.person_row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView amount_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_row);
amount_line = (TextView)row.findViewById(R.id.amount_row);
}
void populateFrom(Cursor c, PaymentHelper helper) {
name_line.setText(helper.getName(c));
amount_line.setText(Integer.toString(helper.sumPerson(c, helper.getName(c))));
}
}
}
SQLiteOpenHelper code to retrieve info
public class PaymentHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "bookkeeping.db";
private static final int SCHEMA_VERSION = 1;
SQLiteDatabase db;
public PaymentHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db = db1;
String sql = "CREATE TABLE IF NOT EXISTS trans (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, date TEXT, amount INT, note TEXT)";
//execute the sql statement
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String name, String date, int amount, String note){
Log.e(name, date + " " + amount);
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
Log.e("Almost", "there");
db.insert("trans", "abc", cv);
Log.e("successfully", "inserted");
}
public Cursor getAll(){
String sql = "SELECT * FROM trans ORDER BY name";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public Cursor getAllNames(){
String sql = "SELECT * FROM users";
Cursor cursor = getReadableDatabase().rawQuery(sql, null);
return cursor;
}
public String getName(Cursor c){
return c.getString(c.getColumnIndex("name"));
}
public String getDate(Cursor c){
return c.getString(c.getColumnIndex("date"));
}
public int getAmount(Cursor c){
return c.getInt(c.getColumnIndex("amount"));
}
public String getNote(Cursor c){
return c.getString(c.getColumnIndex("note"));
}
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("trans", "_id=?", args);
}
public Cursor getById(String id){
String[] args = {id};
String sql = "SELECT * FROM trans WHERE _id=?";
Cursor cursor = getReadableDatabase().rawQuery(sql, args);
return cursor;
}
public void update(String id, String name, String date, int amount, String note){
String[] args = {id};
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("date", date);
cv.put("amount", amount);
cv.put("note", note);
getWritableDatabase().update("trans", cv, "_ID=?", args);
}
public int sumPerson(Cursor c, String name){
int total = 0;
// add up totals
String sql = "SELECT amount FROM trans WHERE name=?";
String[] aname = new String[]{name};
getReadableDatabase().rawQuery(sql,aname);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(name.equals(getName(c))){
total += c.getInt(c.getColumnIndex("amount"));
}
}
return total;
}
}
This is the activity that is receiving the ID from Totals:
I would like it to show only one user (which they selected
from the totals page) with all of their transactions.
public class Detail extends ListActivity {
PaymentHelper helper;
Cursor model = null;
PaymentAdapter adapter = null;
public final static String ID_EXTRA = "com.curtis.bookkeeping._ID";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
helper = new PaymentHelper(this);
model = helper.getAll();
startManagingCursor(model);
adapter = new PaymentAdapter(model);
setListAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.details_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.totals:
startActivity(new Intent(this, Totals.class));
break;
case R.id.users:
startActivity(new Intent(this, Users.class));
break;
case R.id.home:
startActivity(new Intent(this, MainMenu.class));
break;
}
return true;
}
#Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i = new Intent(Detail.this, DeletePayment.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
public class PaymentAdapter extends CursorAdapter {
PaymentAdapter(Cursor c) {
super(Detail.this, c, FLAG_REGISTER_CONTENT_OBSERVER);
}
#Override
public void bindView(View row, Context context, Cursor c) {
PaymentHolder holder = (PaymentHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context context, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
PaymentHolder holder = new PaymentHolder(row);
row.setTag(holder);
return row;
}
}
static class PaymentHolder {
private TextView name_line = null;
private TextView date_line = null;
private TextView amount_line = null;
private TextView note_line = null;
PaymentHolder(View row) {
name_line = (TextView)row.findViewById(R.id.name_line);
amount_line = (TextView)row.findViewById(R.id.amount_line);
date_line = (TextView)row.findViewById(R.id.date_line);
note_line = (TextView)row.findViewById(R.id.note_line);
}
void populateFrom(Cursor c, PaymentHelper helper) {
Log.e(helper.getName(c), Integer.toString(helper.getAmount(c)));
name_line.setText(helper.getName(c));
date_line.setText(helper.getDate(c));
amount_line.setText(Integer.toString(helper.getAmount(c)));
note_line.setText(helper.getNote(c));
}
}
}
I know this is long...but help would be awesome!
I feel like the "PaymentAdapter" needs to be modified to only
read two names if there is only two names. Should I be utilizing
the "UserHelper" db helper to populate this? but when I do, it only
runs one cursor through, and gets a nullpointerexception error because
it is not moving one of the cursors. Should I be making a PaymentAdapter
within PaymentAdapter to generate use of another cursor?
The following SQL query will give you the desired result:
SELECT name, SUM(amount)
FROM trans
GROUP BY name

Obstacle for retrieving data from SQLite database into a ListView(having TextViews) in Android:

I have faced some problems when I want to retrive data from db to some textviews and then put those textvies into a listview.Let me explain I have two columns like date and head in my database.And I want to retrieve those into their each textviews and put these textvies into a listview.I know this may be a silly question for others,but i am new in this field.i know something about SimpleCursorAdapter but dont know how to and where to use it.It may be solve through this.So please guide me.
My Classes::I have created a DBAdapter class for database.MyArrayAdapter class. And a main class calles as Head.java.
DBAdapter.java
public class DBAdapter {
//EditText mHead;
public static final String KEY_ROWID="_id";
public static final String KEY_DATE="date";
public static final String KEY_HEAD="head";
private static final String TAG="DBAdapter";
private static final String DATABASE_NAME="accounting";
private static final String DATABASE_TABLE="accounts";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_CREATE=
"create table accounts (_id integer primary key autoincrement," +
"date datetime not null, head text not null);";
private final Context context;
private DataBaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context=ctx;
DBHelper=new DataBaseHelper(context);
}
private static class DataBaseHelper extends SQLiteOpenHelper {
DataBaseHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
db.execSQL(DATABASE_CREATE);
}catch(SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Updrading database from version "+oldVersion+" to "+newVersion+"," +
"which will destroy all old data");
db.execSQL("drop table if exists accounts");
onCreate(db);
}
}
public DBAdapter open() throws SQLException{
db=DBHelper.getWritableDatabase();
return this;
}
public void close(){
DBHelper.close();
}
**//--insert contact in the database--**
public long insertContact(String date,String head)
{
ContentValues initialvalue=new ContentValues();
initialvalue.put(KEY_DATE, date);
initialvalue.put(KEY_HEAD, head);
return db.insert(DATABASE_TABLE, null, initialvalue);
}
//--delete a particular contact--
public boolean deleteContact(long rowId){
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null)>0;
}
//--Retrieving all the contacts--
public Cursor getAllContacts(){
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE,KEY_HEAD}, null, null, null, null,null);
}
//--Retrieve a particular contact--
public Cursor getContact(long rowId)throws SQLException{
Cursor mCursor=
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,KEY_DATE,KEY_HEAD},
KEY_ROWID + "="+ rowId, null, null, null,
null, null);
if(mCursor != null){
mCursor.moveToFirst();
}
return mCursor;
}
//--update a contact--
public Boolean updateContact(long rowId,String date,String head){
ContentValues args=new ContentValues();
args.put(KEY_DATE, date);
args.put(KEY_HEAD, head);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" +rowId,null)>0;
}
}
MyArrayAdapter.java
public class MyArrayAdapter extends ArrayAdapter<Object>{
private final Context context;
private final String[] values;
//#SuppressWarnings("unchecked")
public MyArrayAdapter(Context context,String[] values){
super(context,R.layout.list_things,values);
this.context=context;
this.values=values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
LayoutInflater inflate=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview=inflate.inflate(R.layout.list_things, parent, false);
TextView mDate=(TextView)rowview.findViewById(R.id.tvdate);
TextView mHead=(TextView)rowview.findViewById(R.id.tvhead);
mDate.setText(values[position]);
mHead.setText(values[position]);
return rowview;
}
}
At last the Head class where I want to do all things
Head.java
public class Head extends ListActivity {
String date = "";
String head;
TextView display;
EditText headname;
ListView list;
LayoutInflater inflate;
Layout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.head);
display=(TextView)findViewById(R.id.tvCurrentDate);
display.setText(date);
// Intent intent=new Intent();
DBAdapter db=new DBAdapter(this);
SimpleCursorAdapter adapter=new SimpleCursorAdapter(Head.this, R.layout.list_things, null, null, null);
//Cursor cursor=getContentResolver().query("/data/data/com.crypto.ranjit/DBAdapter",
//new String []{db., selection, selectionArgs, sortOrder)
Bundle b = getIntent().getExtras();
if (b != null) {
date = b.getString("date");
}
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
headname=(EditText)findViewById(R.id.etHeadname);
date=display.getText().toString();
head=headname.getText().toString();
DBAdapter dba = new DBAdapter(Head.this);
dba.open();
long id = dba.insertContact(date, head);
// id=dba.insertContact(head, date);
dba.close();
}
});
//DBAdapter db=new DBAdapter(Head.this);
//db.open();
}
}
Some silly mistakes here what made me confuse at that time.
Solution:
1:Fill the text views through static values which are define in Head.java.
2:Use ArrayList < HashMap < String, String > > for retrieving data and fill in adapter class.

Categories

Resources