Delete A Row In customAdapter extends BaseAdapter using SQLite - Android - java

I am trying to get a row in my SQLite database to delete on button click. I was successful in getting a row to delete in the ListView, but every time when I try delete from sqlite app crashes.
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
That just delete the item in ListView and not the row in the database.
public class CustomAdapter extends BaseAdapter {
private int custom_adapter;
private Context context;
private ArrayList<Model> mModel;
DatabaseHelper dba = new DatabaseHelper(this.context);
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
}
#Override
public int getCount() {
return mModel.size();
}
#Override
public Object getItem(int position) {
return mModel.get(position);
}
#Override
public long getItemId(int position) {
return mModel.get(position).getId();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(context, R.layout.custom_adapter, null);
final TextView ID = (TextView) v.findViewById(R.id.textViewID);
TextView przejechane = (TextView) v.findViewById(R.id.textViewPrzejechane);
TextView spalone = (TextView) v.findViewById(R.id.textViewSpalanie);
TextView zuzytePaliwo = (TextView) v.findViewById(R.id.textViewUzytepaliwo);
final TextView dataView = (TextView) v.findViewById(R.id.textViewData);
final Button btnDelete = (Button) v.findViewById(R.id.btnDelete);
final ListView listView = (ListView) v.findViewById(R.id.listview);
ID.setText(String.valueOf( mModel.get(position).getId()));
przejechane.setText(String.valueOf( mModel.get(position).getAmount_km()));
spalone.setText(String.valueOf( mModel.get(position).getAvg()));
zuzytePaliwo.setText(String.valueOf( mModel.get(position).getAmount_fuel()));
dataView.setText(String.valueOf( mModel.get(position).getData()));
btnDelete.setTag(position);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dba.removeData(position);
mModel.remove(position);
notifyDataSetChanged();
}
});
return v;
}
here is my DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private SQLiteDatabase mDatabase;
public static final String DATABASE_NAME = "AvgFuel.db";
public static final String TABLE_NAME = "avgFuel_table";
public static final String ID = "ID";
public static final String AMOUNT_FUEL = "AMOUNT_FUEL";
public static final String AMOUNT_KM = "AMOUNT_KM";
public static final String AVG = "AVG";
public static final String DATA = "DATA";
private static final String SELECT_PEOPLE = "SELECT * FROM " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
AMOUNT_FUEL + " REAL, " + AMOUNT_KM + " REAL, " + AVG + " REAL, " + DATA + " TEXT" + ");");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String amount_fuel, String amount_km, double avg){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AMOUNT_FUEL,amount_fuel);
contentValues.put(AMOUNT_KM,amount_km);
contentValues.put(AVG,avg);
contentValues.put(DATA,getNow());
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public void removeData(int id){
SQLiteDatabase db = this.getReadableDatabase();
db.delete(TABLE_NAME, ID + "=" + id , null);
db.close();
}
public ArrayList<Model> getModels() {
ArrayList<Model> model = new ArrayList<Model>();
mDatabase = this.getReadableDatabase();
Cursor cursor = mDatabase.rawQuery(SELECT_PEOPLE, null);
cursor.moveToNext();
for (int i = 0; i <cursor.getCount() ; i++) {
model.add(new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4)));
cursor.moveToNext();
}
cursor.close();
mDatabase.close();
return model;
}
public Model getModel(int id){
mDatabase = this.getReadableDatabase();
String s = "SELECT * FROM" + TABLE_NAME + "WHERE " + ID + "=" + id;
Cursor cursor = mDatabase.rawQuery(s,null);
cursor.moveToFirst();
Model model = new Model(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
cursor.close () ;
mDatabase.close () ;
return model ;
}
private String getNow(){
// set the format to sql date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}

I think the problem is dba creation. Here you just use this adapter context. This should be the context what you get from Activity.
DatabaseHelper dba = new DatabaseHelper(this.context);
Try to use this
public CustomAdapter(Context context, int custom_adapter, ArrayList<Model> mModel) {
this.context = context;
this.mModel = mModel;
this.custom_adapter = custom_adapter;
dba = new DatabaseHelper(context);
}
To get the actual position of recyclerView you can use getAdapterPosition(). Like this
dba.removeData(mModel.get(getAdapterPosition()).getId());
Hope this will help.

Try to change this ..mModel.get(position).getId()
dba.removeData(mModel.get(position).getId());

Related

App is getting crashed when I'm trying to delete Data from database and refreshing ListView

I'm learning android programming and trying to delete data from database using a button in custom ListView but, unfortunately, my App is getting crashed when I hit Yes On Alert DialogBox.
FenceActivity
public class FenceActivity extends AppCompatActivity {
List<Fence> fenceList;
SQLiteDatabase sqLiteDatabase;
ListView listViewFences;
FenceAdapter fenceAdapter;
DataBaseHelper dataBaseHelper;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savedfences);
listViewFences = findViewById(R.id.fencesListView);
fenceList = new ArrayList<>();
showFencesFromDatabase();
}
public void showFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
public void reloadFencesFromDatabase() {
dataBaseHelper = new DataBaseHelper(this);
Cursor cursor = dataBaseHelper.getAllData();
if (cursor.moveToFirst()) {
fenceList.clear();
do {
fenceList.add(new Fence(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getInt(3)));
} while (cursor.moveToNext());
}
cursor.close();
fenceAdapter = new FenceAdapter(FenceActivity.this, R.layout.list_layout_fences, fenceList);
listViewFences.setAdapter(fenceAdapter);
}
}
ShowFencesFromDatabase method I'm using to get Data from the database.
FenceAdapter
public class FenceAdapter extends ArrayAdapter<Fence> {
Context context;
int listLayoutRes;
List<Fence> fenceList;
DataBaseHelper dataBaseHelper;
FenceActivity fenceActivity;
public FenceAdapter(Context context, int listLayoutRes, List<Fence> fenceList) {
super(context, listLayoutRes, fenceList);
this.context = context;
this.listLayoutRes = listLayoutRes;
this.fenceList = fenceList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_layout_fences, null);
}
final Fence fence = fenceList.get(position);
TextView textViewSno = convertView.findViewById(R.id.textViewSnoLabel);
TextView textViewLat = convertView.findViewById(R.id.textViewLatitudeValue);
TextView textViewLon = convertView.findViewById(R.id.textViewLongitudeValue);
TextView textViewRadi = convertView.findViewById(R.id.textViewRadiusValue);
textViewSno.setText(Integer.toString(fence.getSno()));
textViewLat.setText(String.valueOf(fence.getLat()));
textViewLon.setText(String.valueOf(fence.getLon()));
textViewRadi.setText(Integer.toString(fence.getRadius()));
Button buttonDel = convertView.findViewById(R.id.buttonDeleteFence);
buttonDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper = new DataBaseHelper(context);
fenceActivity = (FenceActivity)context;
dataBaseHelper.deleteDataById(fence);
fenceActivity.reloadFencesFromDatabase();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
return convertView;
}
DatabaseHelper Class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DataBaseHelper";
public static final String DB_NAME = "FenceDatabase";
private static final String TABLE_NAME = "FenceData";
private static final String col1 = "Sno";
private static final String col2 = "Latitude";
private static final String col3 = "Longitude";
private static final String col4 = "Radius";
Context context;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (" + col1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + col2 + " REAL , " + col3 + " REAL , " + col4 + " INTEGER)";
sqLiteDatabase.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean addData(Double lat, Double lon, int radi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, lat);
contentValues.put(col3, lon);
contentValues.put(col4, radi);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
return true;
}
public Cursor getAllData() {
String query = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
return cursor;
}
public void deleteDataById(Fence fence) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String sql = "DELETE FROM FenceData WHERE Sno = ?";
sqLiteDatabase.execSQL(sql, new Integer[]{fence.getSno()});
}
}
Fence class
public class Fence {
int radius,sno;
double lat,lon;
public Fence( int sno,double lat, double lon,int radius) {
this.radius = radius;
this.sno = sno;
this.lat = lat;
this.lon = lon;
}
public int getRadius() {
return radius;
}
public int getSno() {
return sno;
}
public double getLat() {
return lat;
}
public double getLon() {
return lon;
}
}
Errors
2019-06-30 19:06:08.658 22783-22875/com.abhishakkrmalviya.fencetest E/LB: fail to open file: No such file or directory
2019-06-30 19:06:11.473 22783-22783/com.abhishakkrmalviya.fencetest E/SchedPolicy: set_timerslack_ns write failed: Operation not permitted
What steps should I take to make App work properly, I mean to delete data from the database?
Initialise dataBaseHelper = new DataBaseHelper(context); before invoking dataBaseHelper.deleteDataById();
The problem is within FenceAdapter.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dataBaseHelper.deleteDataById();
fenceActivity.showFencesFromDatabase();
}
});
The problem is that dataBaseHelper is not initialized before its usege.
It can be solve by adding a line dataBaseHelper = new DataBaseHelper(context); at the end of adapter's constructor.

Delete Both row of list items on recyclerView and SQLite database

I am a beginner at programming, I want to make a delete button on every items list on recyclerView. I got some references from stack overflow, and its work for the deleted item only at the activity (layout), but when i run the activity again the The selected item showed again.
I found some related articles on stackoverflow and make the method to delete from the SQLite. But my app crushed "unfortunetly app has stopped" every time I call the delete function.
I hope someone can help me to figure it out.
here is my databasehelper class
public class DatabaseHelperClass extends SQLiteOpenHelper {
Log cat Database
public static String log = "DatabaseHelper";
//Databse version
public static final int DATABASE_VERSION = 1;
//Database name
public static final String DATABSE_NAME = "dbPig";
//Tables Name
public static final String TABLE_PIGINFO = "tb_pigInfo";
//Common and PigInfo Column Names
public static final String KEY_ID = "id";
public static final String KEY_NAMA = "nama";
public static final String KEY_TANGGAL_PENDAFTARAN = "tanggal_pendaftaran";
//table create statement
//table pig Info
public static final String CREATE_TABLE_PIGINFO = "CREATE TABLE "
+ TABLE_PIGINFO + "(" + KEY_ID + " INTEGER," + KEY_NAMA
+ " TEXT," + KEY_TANGGAL_PENDAFTARAN
+ " TEXT" + ")";
public DatabaseHelperClass(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//creating requaired table
db.execSQL(CREATE_TABLE_PIGINFO);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PIGINFO);
// create new tables
onCreate(db);
}
public void insertdata(String nama, String tanggal_pendaftaran) {
System.out.print("Tersimpan" + TABLE_PIGINFO);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAMA, nama);
contentValues.put(KEY_TANGGAL_PENDAFTARAN, tanggal_pendaftaran);
db.insert(TABLE_PIGINFO, null, contentValues);
}
public List<PigInfoTable> getdata() {
List<PigInfoTable> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_PIGINFO + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
PigInfoTable pigInfoTable = null;
while (cursor.moveToNext()) {
pigInfoTable = new PigInfoTable();
String nama = cursor.getString(cursor.getColumnIndexOrThrow("nama"));
String tanggal_pendaftaran = cursor.getString(cursor.getColumnIndexOrThrow("tanggal_pendaftaran"));
pigInfoTable.setNama(nama);
pigInfoTable.setTanggal_pendaftaran(tanggal_pendaftaran);
stringBuffer.append(pigInfoTable);
data.add(0, pigInfoTable);
}
for (PigInfoTable mo : data) {
Log.i("Hellomo", "" + mo.getNama());
}
return data;
}
public void delete(int position) {
SQLiteDatabase db = this.getWritableDatabase();
String table = TABLE_PIGINFO;
String whereClause = KEY_ID;
String [] whereArgs = new String[] {String.valueOf(position)};
db.delete (table, whereClause, whereArgs);
}
and here my adapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.Myholder> {
DatabaseHelperClass databaseHelper;
List <PigInfoTable> pigInfoTablesArrayList;
public RecycleAdapter(List <PigInfoTable> pigInfoTablesArrayList) {
this.pigInfoTablesArrayList = pigInfoTablesArrayList;
}
class Myholder extends RecyclerView.ViewHolder{
private TextView nama, tanggal_pendaftaran;
private Button delete;
public Myholder(View itemView) {
super(itemView);
nama = (TextView) itemView.findViewById(R.id.nama1);
tanggal_pendaftaran = (TextView) itemView.findViewById(R.id.tanggal1);
delete = (Button) itemView.findViewById(R.id.delete);
}
}
#Override
public Myholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_itempigview,null);
return new Myholder(view);
}
#Override
public void onBindViewHolder(Myholder holder, final int position) {
PigInfoTable pigInfoTable= pigInfoTablesArrayList.get(position);
holder.nama.setText(pigInfoTable.getNama());
holder.tanggal_pendaftaran.setText(pigInfoTable.getTanggal_pendaftaran());
holder.itemView.setClickable(true);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return pigInfoTablesArrayList.size();
}
I am trying some other solution but the same error occurred which's
null object references on
Position
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
at com.example.newbreedy.RecycleAdapter$1.onClick(RecycleAdapter.java:66)
thank you
com.example.newbreedy.DatabaseHelperClass.delete(int)' on a null object reference
because you have not initialized the reference of
DatabaseHelperClass databaseHelper;
So Add.
databaseHelper =new DatabaseHelperClass (context);
in your recycler adapter
In your code you are sending adapter position so in place of position send KEY_ID.
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyDataSetChanged();
First you have to initialize your DatabaseHelperClass in your adapter like this,
databaseHelper =new DatabaseHelperClass (context);
Than you need to call the delete function and inform the adapter about the removed item like this,
databaseHelper.delete(position);
pigInfoTablesArrayList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, pigInfoTablesArrayList.size());

can't get to show data from a database sqlite with a requirement JAVA ANDROID STUDIO

i can't get my data to show on my ListView. i created database handler with a query that says: "SELECT * FROM TABLE_NAME WHERE COLUMN_USERNAME = '"+Username+"'". i want to show Data that have the username i want only. But i cant seem to get it work. here is the code.
ViewEvent class with the List View
public class ViewEvent extends Activity {
private static String z = "";
private static final int _EDIT = 0, _DELETE = 1; // constants to be used later
static int longClickedItemIndex;
static List<Event> events = new ArrayList<Event>();
ArrayAdapter<Event> eventsAdapter;
ListView listViewEvents;
static DatabaseHandlerEvent helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_event);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Type Keys Filled.ttf");
TextView myTextview = (TextView) findViewById(R.id.textViewHead4);
myTextview.setTypeface(myTypeFace);
helper = new DatabaseHandlerEvent(getApplicationContext());
listViewEvents = (ListView) findViewById(R.id.listView);
registerForContextMenu(listViewEvents);
listViewEvents.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
}
);
populateList();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Username = prfs.getString("Username", "");
if (helper.getEventCount() != 0 && events.size() == 0) {
events.addAll(helper.getAllEvent(Username));
}
}
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
public void onButtonClick(View v){
if(v.getId() == R.id.bSignoutb){
Toast so = Toast.makeText(ViewEvent.this, "Signing out.. Redirecting to Login Page..." , Toast.LENGTH_SHORT);
so.show();
Intent i = new Intent(ViewEvent.this, MainActivity.class);
startActivity(i);
}
if(v.getId() == R.id.Bback){
Intent i = new Intent(ViewEvent.this, CreateEvent.class);
startActivity(i);
}
}
private void populateList() {
eventsAdapter = new eventListAdapter();
listViewEvents.setAdapter(eventsAdapter);
}
public class eventListAdapter extends ArrayAdapter<Event> {
public eventListAdapter() {
super(ViewEvent.this, R.layout.listview_event, events);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
}
Event currentEvent = events.get(position);
TextView name = (TextView) view.findViewById(R.id.textViewEventName);
name.setText(currentEvent.getName());
TextView location = (TextView) view.findViewById(R.id.textViewLocation);
location.setText(currentEvent.getLocation());
TextView date = (TextView) view.findViewById(R.id.textViewDate);
date.setText(currentEvent.getDate());
TextView description = (TextView) view.findViewById(R.id.textViewDescription);
description.setText(currentEvent.getDescription());
TextView time = (TextView) view.findViewById(R.id.textViewTime);
time.setText(currentEvent.getTime());
TextView testnia = (TextView) view.findViewById(R.id.testnia);
testnia.setText(currentEvent.getUsername());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.huhu);// find a suitable icon
menu.setHeaderTitle("Event options:");
menu.add(Menu.NONE, _EDIT, Menu.NONE, "Edit Event");
menu.add(Menu.NONE, _DELETE, Menu.NONE, "Delete Event");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case _EDIT:
// editing a contact
Intent editContactIntent = new Intent(getApplicationContext(), EditEvent.class);
startActivityForResult(editContactIntent, 2); // reqcode=2
break;
case _DELETE:
helper.deleteEvent(events.get(longClickedItemIndex));
events.remove(longClickedItemIndex);
eventsAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
}
And this is my DataBaseHelperEvent class
public class DatabaseHandlerEvent extends SQLiteOpenHelper {
static DatabaseHelperUser helper;
Event event;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Events";
private static final String TABLE_NAME = "Events";
private static final String COLUMN_ID = "id",
COLUMN_NAME = "name", COLUMN_LOCATION = "location", COLUMN_DATE = "date",
COLUMN_TIME ="time", COLUMN_DESCRIPTION = "description", COLUMN_USERNAME = "username";
SQLiteDatabase db;
public DatabaseHandlerEvent(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " +
COLUMN_DATE + " TEXT, " + COLUMN_TIME + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT, " + COLUMN_USERNAME + " TEXT)"
);
}
public long createEvent (Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
values.put(COLUMN_USERNAME, event.getUsername());
long result = db.insert(TABLE_NAME, null, values);
db.close();
return result;
}
public int updateEvent(Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
int rowsAffected = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
public List<Event> getAllEvent(String Username) {
List<Event> events = new ArrayList<Event>();
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+COLUMN_USERNAME+" = "+ "'"+Username+"'", null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4),
cursor.getString(5), cursor.getString(6)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return events;
}
public int getEventCount() {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int deleteEvent(Event event) {
db = this.getWritableDatabase();
int rowsAffected = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
So whenever i show my ListView, it will show nothing. How can i show the data that only have a specific username i want? thanks! Sorry for my bad english

Sum int value of column of database Android

I want to sum integer value of a column.
my code use to sum:
public int getTotal() {
// TODO Auto-generated method stub
int sum=0;
Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
if(cursor.moveToFirst()) {
sum=cursor.getInt(0);
}
return sum;
}
other way that I tried:
public int sum() {
x=0;
for (int i =list.size(); i>0 ; i--) {
Log.e("sumprice","");
x = x +list.get(i).getName();
}
return x;
}
and DATABASE HELPER
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_NUM = "num";
private static final String COLUMN_TYPE = "type";
private static final String COLUMN_CODE = "CODE";
public static final String COLUMN_ESME = "ESME";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + "INTEGER," +
COLUMN_VALUE + "INTEGER," +
COLUMN_NUM + " TEXT," +
COLUMN_TYPE + " TEXT," +
COLUMN_CODE + " TEXT," +
COLUMN_ESME + " TEXT" +
");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,8);
Log.i(TAG, "Object created.");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHelper.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);
}
public String getTableName() {
return TABLE_NAME;
}
public String getRowIdName() {
return COLUMN_ID;
}
}
DATABASE handler
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String NUM = "num";
static final String TYPE = " type";
static final String CODE = "code";
static final String ESME = "esme";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertContact(contac contacts) {
database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
Log.e("D","1.1");
cv.put(NAME,contacts.getName());
cv.put(VALUE,contacts.getPhoneNumber());
cv.put(NUM,contacts.getNUM());
cv.put(TYPE,contacts.getTYPE());
cv.put(CODE,contacts.getCODE());
cv.put(ESME,contacts.getESME());
Log.e("D","1.2");
// Log.e("",cv);
database.insert(dbHelper.getTableName(), NAME, cv);
Log.e("","1.8");
Log.i(TAG, "Contact added successfully.");
Log.e("","1.9");
}
public void deleteContact(long id) {
database.delete(dbHelper.getTableName(), dbHelper.getRowIdName() + "=" + id, null);
}
public void updateContact(long id) {
ContentValues cv = new ContentValues();
cv.put(NAME, 3123123);
cv.put(VALUE, "12345");
cv.put(NUM, "123543");
cv.put(TYPE, "benzini");
cv.put(CODE, "123543");
cv.put(ESME, "benzini");
database.update(dbHelper.getTableName(), cv, dbHelper.getRowIdName() + "=" + id, null);
}
public List<contac> getAllContacts() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Log.e("D","1.9");
List<contac> contacts = new ArrayList<contac>();
Log.e("D","1.9");
Cursor cursor = database.query(dbHelper.getTableName(),null, null, null, null, null, null);
Log.e("D","1.9");
cursor.moveToFirst();
Log.e("D","1.9");
while (!cursor.isAfterLast()) {
Log.e("D","1.9");
contac contact= cursorTocontac(cursor);
Log.e("D","1.9");
contacts.add(contact);
Log.e("D","1.9");
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return contacts;
}
private contac cursorTocontac(Cursor cursor) {
contac contacts = new contac(0, 0, 0, TAG, TAG, TAG, TAG);
Log.e("","2");
contacts.setId(cursor.getLong(0));
contacts.setName(cursor.getInt(1));
contacts.setPhoneNumber(cursor.getInt(2));
contacts.setNUM(cursor.getString(3));
contacts.setTYPE(cursor.getString(4));
contacts.setCODE(cursor.getString(5));
contacts.setESME(cursor.getString(6));
Log.e("","2.1");
return contacts;
}
public void clearTable() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.delete(dbHelper.getTableName(), null, null);
// helper is object extends SQLiteOpenHelper
}
public long getNAMESum() {
database = dbHelper.getWritableDatabase();
Log.e("F","1.9");
long result = 0;
Log.e("F","1.9.1");
Cursor cur = database.rawQuery("SELECT SUM(COLUMN_NAME) FROM myTable", null);
Log.e("F","1.9.2");
if(cur.moveToFirst())
{
return cur.getInt(0);
}
cur.close();
return result;
}
public int getTotal() {
// TODO Auto-generated method stub
int sum=0;
Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
if(cursor.moveToFirst()) {
sum=cursor.getInt(0);
}
return sum;
}
public void delete(String id)
{
database = dbHelper.getWritableDatabase();
database.delete(dbHelper.getTableName(), "_id=?", new String[]{id});
database.close();
}
}
List Adapter
public class ListAdapter extends ArrayAdapter<contac> {
private final String TAG = "*** ListAdapter ***";
Context context;
LayoutInflater myInflater;
List<contac> list;
CheckBox checkBox6;
int x;
public ListAdapter(Context context, int resource,
List<contac> list) {
super(context, resource, list);
this.context = context;
this.list = list;
myInflater = LayoutInflater.from(context);
this.context = context;
Log.i(TAG, "Adapter setuped successfully.");
}
public void setData(List<contac> list) {
this.list = list;
Log.i(TAG, "Data passed to the adapter.");
}
public void clear(List<contac> list) {
list.clear();
Log.i(TAG, "Data passed to the adapter.");
}
#Override
public int getCount() {
return list.size();
}
public void remove(contac contac) {
list.remove(contac);
updateList(list);
setData(list);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.list_adapter, null);
holder = new ViewHolder();
// holder.tvId = (TextView) convertView.findViewById(R.id.tvId);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPhone = (TextView) convertView.findViewById(R.id.tvPhone);
holder.tvnum = (TextView) convertView.findViewById(R.id.tvnum);
holder.tvtype = (TextView) convertView.findViewById(R.id.tvtype);
holder.tvcode = (TextView) convertView.findViewById(R.id.tvcode);
holder.tvesme = (TextView) convertView.findViewById(R.id.tvesme);
holder.checkBox6 = (CheckBox)convertView.findViewById(R.id.checkBox6);
holder.checkBox6
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
contac element = (contac) holder.checkBox6.getTag();
element.setSelected(buttonView.isChecked());
}
});
convertView.setTag(holder);
holder.checkBox6.setTag(list.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).checkBox6.setTag(list.get(position));
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
NumberFormat format = NumberFormat.getCurrencyInstance();
// holder.tvId.setTag(list.get(position).getIdInString());
// holder.tvId.setText(list.get(position).getIdInString());
holder.tvName.setText(format.format(list.get(position).getName()));
holder.tvPhone.setText(format.format(list.get(position).getPhoneNumber()));
holder.tvnum.setText(list.get(position).getNUM());
holder.tvtype.setText(list.get(position).getTYPE());
holder.tvcode.setText(list.get(position).getCODE());
holder.tvesme.setText(list.get(position).getESME());
holder.checkBox6.setChecked(list.get(position).isSelected());
return convertView;
}
static class ViewHolder {
// TextView tvId;
TextView tvName;
TextView tvPhone;
TextView tvnum;
TextView tvtype;
TextView tvcode;
TextView tvesme;
CheckBox checkBox6;
}
public int sum() {
x=0;
for (int i =list.size(); i>0 ; i--) {
Log.e("sumprice","");
x = x +list.get(i).getName();
}
return x;
}
public List<contac> getcontac() {
return list;
}
public void updateList(List<contac> list) {
this.list = list;
notifyDataSetChanged();
}
}
and my code to set in text view
int sum=dbHandler.getTotal();
txtsumprice = (TextView) view.findViewById(R.id.sumprice);
NumberFormat format = NumberFormat.getCurrencyInstance();
txtsumprice.setText(""+format.format(sum));
can solve my problem I very try to do it but not worked
you have an SQL syntax error (...myTotalFROM...):
Cursor cursor = database.rawQuery("SELECT Sum(name)myTotalFROM "+dbHelper.getTableName(), null);
should be:
Cursor cursor = database.rawQuery("SELECT Sum(name) AS myTotal FROM "+dbHelper.getTableName(), null);

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

Categories

Resources