Android Checkbox with Listview and SQLite - android

I have created an application that a user can store player information. I am now looking to have a checkbox to confirm that the player is available. I know that sqlite cannot store a boolean value so was wondering if someone could help me with a way around this. I have added the checkbox but at the moment i have it stored as a 0 value with no functionality.
Below is the display adapter:
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email;
//private ArrayList<String> ConFirm;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
Here is the display call from the main activity:
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And finally the Dbhelper:
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TEXT DEFAULT 0)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
If you would like any more information or code just let me know. Thankyou in advance.
------UPDATED------
Below is the db update function from the FoursFragment.java class:
//add
view.findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//Update
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getActivity(),
AddActivity.class);
i.putExtra("Confirm", user_cOnfirm.get(arg2));
i.putExtra("Mail", user_eMail.get(arg2));
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//delete
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
build = new AlertDialog.Builder(getActivity());
build.setTitle("Delete " + user_fName.get(arg2) + " "
+ user_lName.get(arg2) + " " + user_eMail.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Toast.makeText(
getActivity(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
return view;
}
}}
#Override
public void onResume() {
displayData();
super.onResume();
}
//display
#SuppressLint("UseValueOf")
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{

At first you should change your database table. Don't use the type 'TEXT' to store the boolean, use the type 'TINYINT' instead of that. TINYINT provides 1 byte to save the value. Because of that you can define a constraint (the check at the end), to avoid saving values like 3.
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
To read the value from the database change the loop.
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
You request an Integer instead of a String as returning value from the database. If you need to get a boolean, you can add the comparision with 1.
Just a tip, you don't need your do-while. The cursor points at the beginning on a position before the first entry. With the call of moveToNext for the first time, you move it to the first entry. If there's no entry, the loop will be skipped.
You need to change the type of the ArrayList to Boolean (with a big B).
Add the initialization with the value for the checkbox
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos));
These are the necessary changes. I add the changed code below (not tested)
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> Email; // better name it email
private ArrayList<Boolean> ConFirm; //better name it confirm, it's one word
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> email, ArrayList<String> check) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.Email = email;
this.ConFirm = check;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder; // the m shows that this shall be a member variable, this is just local for this method.
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_eMail = (TextView) child.findViewById(R.id.txt_eMail);
mHolder.txt_cOnfirm = (CheckBox) child.findViewById(R.id.txt_cOnfirm);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_eMail.setText(Email.get(pos));
mHolder.txt_cOnfirm.setChecked(ConFirm.get(pos).booleanValue());
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_eMail;
CheckBox txt_cOnfirm;
}
}
The part from your main activity
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_eMail.clear();
user_cOnfirm.clear();
while(mCursor.moveToNext()) {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_eMail.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_EMAIL)));
user_cOnfirm.add(new Boolean((mCursor.getInt(mCursor.getColumnIndex(DbHelper.KEY_CONFIRM)) == 1)));
}
DisplayAdapter disadpt = new DisplayAdapter(getActivity(),userId, user_fName, user_lName, user_eMail, user_cOnfirm);
userList.setAdapter(disadpt);
mCursor.close();
}
{
}
And your DBHelper
public class DbHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_EMAIL="email";
public static final String KEY_CONFIRM="confirm";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 2); // The 2 is the version. It have to be higher than the old, because we changed the database schema
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE " +TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_EMAIL+" TEXT, "+KEY_CONFIRM+" TINYINT DEFAULT 0, check("+KEY_CONFIRM+"=0 OR "+KEY_CONFIRM+"=1)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
I hope this solves your problem, if not feel free to ask another question, if please rate this answer as positive.
P.s.:
Take a look at the coding guidelines: https://source.android.com/source/code-style.html

Related

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

Remove item from database in recyclerview

I would like to add a feature that would allow me to remove a row from my recyclerview/database.
This feature is integrate to each item of my recyclerview as show in the following picture :
MySQLite.java:
public class MySQLite extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "character";
private static final int DATABASE_VERSION = 1;
private static final String CHARACTER_TABLE = "Ichar";
private static final String CHAR_TABLE = "create table " + CHARACTER_TABLE + "(id INTEGER PRIMARY KEY AUTOINCREMENT, nom TEXT, prenom TEXT , numero TEXT)";
Context context;
public MySQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CHAR_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public void InsererBDD(String nom, String prenom, String numero) {
Log.d("insert", "before insert");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues entree = new ContentValues();
entree.put("nom", nom);
entree.put("prenom", prenom);
entree.put("numero", numero);
db.insert(CHARACTER_TABLE, null, entree);
db.close();
Toast.makeText(context, "insérer entrée", Toast.LENGTH_LONG);
Log.i("insert", "after insert");
db.close();
}
public List<Character> donneesBDD() {
List<Character> modelList = new ArrayList<Character>();
String query = "select * FROM " + CHARACTER_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Character model = new Character();
model.setCharacter_Id(cursor.getInt(0));
model.setNom(cursor.getString(1));
model.setPrenom(cursor.getString(2));
model.setNumero(cursor.getString(3));
modelList.add(model);
} while (cursor.moveToNext());
}
Log.d("donnee character", modelList.toString());
return modelList;
}
public void supprimerLigne(int character_Id){
SQLiteDatabase db = getWritableDatabase();
db.delete(CHARACTER_TABLE , "id" + " = ?", new String[] { String.valueOf(character_Id)});
db.close();
}
public Character getCharacterById(int Id) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT " +
"nom" + "," +
"prenom" + "," +
"numero" +
" FROM " + CHARACTER_TABLE
+ " WHERE " +
"id" + "=?";
Character character = new Character();
Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(Id)});
if (cursor.moveToFirst()) {
do {
character.character_Id = cursor.getInt(cursor.getColumnIndex("id"));
character.nom = cursor.getString(cursor.getColumnIndex("nom"));
character.prenom = cursor.getString(cursor.getColumnIndex("prenom"));
character.numero = cursor.getString(cursor.getColumnIndex("numero"));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return character;
}
}
MyAdapter.java:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
static List<Character> characters;
static Context context;
MyAdapter(Context context,List<Character> characters)
{
this.characters = new ArrayList<Character>();
this.context = context;
this.characters = characters;
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int itemType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_cell, null);
MyViewHolder myViewHolder = new MyViewHolder(itemLayoutView);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
holder.nom.setText(characters.get(position).getNom());
holder.prenom.setText(characters.get(position).getPrenom());
}
#Override
public int getItemCount() {
return characters.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener,View.OnClickListener, MenuItem.OnMenuItemClickListener {
public TextView nom;
public TextView prenom;
public ImageButton delete;
public MyViewHolder(final View itemLayoutView) {
super(itemLayoutView);
nom = ((TextView) itemLayoutView.findViewById(R.id.nom));
prenom = ((TextView) itemLayoutView.findViewById(R.id.prenom));
delete = (ImageButton) itemView.findViewById(R.id.delete);
itemLayoutView.setOnClickListener(this);
itemLayoutView.setOnCreateContextMenuListener(this);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(getAdapterPosition());
}
});
}
#Override
public void onClick(View view) {
Intent intent = new Intent(context, personne.class);
Bundle extras = new Bundle();
extras.putInt("position", getAdapterPosition());
intent.putExtras(extras);
context.startActivity(intent);
Toast.makeText(MyAdapter.context, "Vous avez sélectionné un item" + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("");
menu.add(0, v.getId(), 0, "Modifier Contact");
menu.add(0, v.getId(), 0, "Supprimer Contact");
}
#Override
public boolean onMenuItemClick(MenuItem item)
{
return true;
}
}
}
can you guide me?
Thanks a lot.
You need to remove the item from your array and then notifyDataSetChanged()
fragmentOrActivity.yourArray.remove(holder.getAdapterPosition());
fragmentOrActivity.yourAdapter.notifyDataSetChanged();
Hope that helps :-)
You should write your code in onBindViewHolder method like below.
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MySQLite sqlite = new MySQLite(context);
sqlite.supprimerLigne(characters.get(position).getId());
}
});

Alert dialog delete a row on ListView Item click

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?

how to display data from sqlite in custom listfragment

I want to display data from sqlite database and I will show to listfragment, but until now have not been able to be displayed
Class Barang.java
public class Barang {
private long id;
private String nama_barang;
private String merk_barang;
private String harga_barang;
public Barang()
{
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the nama_barang
*/
public String getNama_barang() {
return nama_barang;
}
/**
* #param nama_barang the nama_barang to set
*/
public void setNama_barang(String nama_barang) {
this.nama_barang = nama_barang;
}
/**
* #return the merk_barang
*/
public String getMerk_barang() {
return merk_barang;
}
/**
* #param merk_barang the merk_barang to set
*/
public void setMerk_barang(String merk_barang) {
this.merk_barang = merk_barang;
}
/**
* #return the harga_barang
*/
public String getHarga_barang() {
return harga_barang;
}
/**
* #param harga_barang the harga_barang to set
*/
public void setHarga_barang(String harga_barang) {
this.harga_barang = harga_barang;
}
#Override
public String toString()
{
return id +" "+ nama_barang +" "+ merk_barang + " "+ harga_barang;
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper{
public static final String TABLE_NAME = "data_inventori";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nama_barang";
public static final String COLUMN_MERK = "merk_barang";
public static final String COLUMN_HARGA = "harga_barang";
private static final String db_name ="inventori.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID +" integer primary key autoincrement, "
+ COLUMN_NAME+ " varchar(50) not null, "
+ COLUMN_MERK+ " varchar(50) not null, "
+ COLUMN_HARGA+ " varchar(50) not null);";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(db_create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(DBHelper.class.getName(),"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
DBDataSource.java
public class DBDataSource {
private SQLiteDatabase database;
private DBHelper dbHelper;
private String[] allColumns = { DBHelper.COLUMN_ID,
DBHelper.COLUMN_NAME, DBHelper.COLUMN_MERK,DBHelper.COLUMN_HARGA};
public DBDataSource(Context context)
{
dbHelper = new DBHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Barang createBarang(String nama, String merk, String harga) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, nama);
values.put(DBHelper.COLUMN_MERK, merk);
values.put(DBHelper.COLUMN_HARGA, harga);
long insertId = database.insert(DBHelper.TABLE_NAME, null,
values);
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, DBHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Barang newBarang = cursorToBarang(cursor);
cursor.close();
return newBarang;
}
private Barang cursorToBarang(Cursor cursor)
{
Barang barang = new Barang();
barang.setId(cursor.getLong(0));
barang.setNama_barang(cursor.getString(1));
barang.setMerk_barang(cursor.getString(2));
barang.setHarga_barang(cursor.getString(3));
return barang;
}
public ArrayList<Barang> getAllBarang() {
ArrayList<Barang> daftarBarang = new ArrayList<Barang>();
Cursor cursor = database.query(DBHelper.TABLE_NAME,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Barang barang = cursorToBarang(cursor);
daftarBarang.add(barang);
cursor.moveToNext();
}
cursor.close();
return daftarBarang;
}
public Barang getBarang(long id)
{
Barang barang = new Barang();
Cursor cursor = database.query(DBHelper.TABLE_NAME, allColumns, "_id ="+id, null, null, null, null);
cursor.moveToFirst();
barang = cursorToBarang(cursor);
cursor.close();
return barang;
}
public void updateBarang(Barang b)
{
String strFilter = "_id=" + b.getId();
ContentValues args = new ContentValues();
args.put(DBHelper.COLUMN_NAME, b.getNama_barang());
args.put(DBHelper.COLUMN_MERK, b.getMerk_barang());
args.put(DBHelper.COLUMN_HARGA, b.getHarga_barang() );
database.update(DBHelper.TABLE_NAME, args, strFilter, null);
}
public void deleteBarang(long id)
{
String strFilter = "_id=" + id;
database.delete(DBHelper.TABLE_NAME, strFilter, null);
}
}
MasterBarang.java
public class MasterBarang extends ListFragment implements OnItemLongClickListener {
private DBDataSource dataSource;
private ImageButton bTambah;
private ArrayList<Barang> values;
private Button editButton;
private Button delButton;
private AlertDialog.Builder alertDialogBuilder;
public MasterBarang(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_masterbarang, container, false);
bTambah = (ImageButton) rootView.findViewById(R.id.button_tambah);
bTambah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), CreateData.class);
startActivity(intent);
getActivity().finish();
}
});
ListView lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnItemLongClickListener(this);
return rootView;
}
public void OnCreate(Bundle savedInstanceStat){
dataSource = new DBDataSource(getActivity());
dataSource.open();
values = dataSource.getAllBarang();
ArrayAdapter<Barang> adapter = new ArrayAdapter<Barang>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapter, View v, int pos,
final long id) {
final Barang b = (Barang) getListAdapter().getItem(pos);
alertDialogBuilder.setTitle("Peringatan");
alertDialogBuilder
.setMessage("Pilih Aksi")
.setCancelable(false)
.setPositiveButton("Ubah",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
switchToEdit(b.getId());
dialog.dismiss();
}
})
.setNegativeButton("Hapus",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dataSource.deleteBarang(b.getId());
dialog.dismiss();
getActivity().finish();
startActivity(getActivity().getIntent());
}
}).create().show();
return false;
}
public void switchToEdit(long id)
{
Barang b = dataSource.getBarang(id);
Intent i = new Intent(getActivity(), EditData.class);
Bundle bun = new Bundle();
bun.putLong("id", b.getId());
bun.putString("nama", b.getNama_barang());
bun.putString("merk", b.getMerk_barang());
bun.putString("harga", b.getHarga_barang());
i.putExtras(bun);
finale();
startActivity(i);
}
public void finale()
{
MasterBarang.this.getActivity().finish();
dataSource.close();
}
#Override
public void onResume() {
dataSource.open();
super.onResume();
}
#Override
public void onPause() {
dataSource.close();
super.onPause();
}
}
in simple not displayed
Here is the example code.
First create a layout for one list row.
example : list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp"
>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/merk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_marginTop="5dp" />
<TextView
android:id="#+id/harga"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/merk"
android:layout_marginTop="5dp"/>
</RelativeLayout>
After creating this list_row.xml layout, create a adapter class.
create CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ArrayList<Barang> barangList;
public CustomListAdapter(Activity activity, ArrayList<Barang> barangList) {
this.activity = activity;
this.barangList = barangList;
}
/*
get count of the barangList
*/
#Override
public int getCount() {
return barangList.size();
}
#Override
public Object getItem(int location) {
return barangList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
/*
inflate the items in the list view
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_row, null);
}
/*
creating objects to access the views
*/
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView merk = (TextView) convertView.findViewById(R.id.merk);
TextView harga = (TextView) convertView.findViewById(R.id.harga);
// getting barang data for the row
Barang barang = barangList.get(position);
name.setText(barang.getNama_barang());
merk.setText(barang.getMerk_barang());
harga.setText(barang.getHarga_barang());
return convertView;
}}
Now in your MasterBarang.java, put the following code in your onCreate method.
values = dataSource.getAllBarang();
CustomListAdapter adapter;
adapter = new CustomListAdapter(getActivity(), values);
setListAdapter(adapter);
Now run the application.. Cheers !
You are using simple list templete as a list view. But in case of custom list view, you should create your custom list model and "BaseAdapter" for the custom list model.
Below links will help you to make custom list view in easier way.
https://www.caveofprogramming.com/guest-posts/custom-listview-with-imageview-and-textview-in-android.html
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
The problem is you are closing your database in onPause() method, so the reference of the database will get destroyed. Then, you again trying to open the database in onResume() method. So here the null pointer exception occurs.
Solution:
change your onResume() method like this.
#Override
public void onResume() {
dataSource = new DBDataSource(getActivity());
dataSource.open();
super.onResume();
}
Now check it and if you got any error please post it here,.

Listview empty after insert a field in db?

I was looking for an example/tutorial to insert datas in a sqlLite db and display the datas in a listview. Well this is a good example: http://androidsolution4u.blogspot.it/2013/09/android-populate-listview-from-sqlite.html And it works. I implemented the code in mine and works. The problem is that if i want insert another one filed nothing appears in the listview and the activity is empty.I added a field called address as string like the others and in every part of code i added what is need copying from the others (of course changing the names). But when i try to add the item not appears. Of course i update the xml files with new field. I can't write the whole code because it's too much. But if someone can help me to find a way out i'll write the part of code required. Thanks
EDIT: the code is equal at the example but with the field i need to add.
The DisplayActivity
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_address = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("address", user_address.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2) + " " + user_address(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+ user_address.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_address.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName, user_address);
userList.setAdapter(disadpt);
mCursor.close();
}
}
The DisplayAdapter
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> address;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> address) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.address = address;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.txt_address = (TextView) child.findViewById(R.id.txt_address);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.txt_address.setText(address.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView txt_address;
}
}
The DbHelper
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";
public static final String KEY_ADDRESS="address";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_ADDRESS+" 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);
}
}
And the AddActivity
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,edit_address;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,address;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
edit_address=(EditText)findViewById(R.id.address_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
address=getIntent().getExtras().getString("address");
edit_first.setText(fname);
edit_last.setText(lname);
edit_address.setText(address);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
address=edit_address.getText().toString().trim();
if(fname.length()>0 && lname.length()>0 && address.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_ADDRESS,address );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
That's all. I can't find the problem. Helps?
Forgotten in displayData() user_address.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ADDRESS)));

Categories

Resources