Android Listview not updating after delete item - java

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();

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 A Row In customAdapter extends BaseAdapter using SQLite - Android

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());

Adding item in RecyclerView Fragment [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Apologies first of all because it is going to be a long question.
I am creating a to do list using 2 RecyclerViews in 2 fragments following is the code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TaskDbHelper mHelper;
public Tab1 incompleteTasks;
public Tab2 completedTasks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
final EditText taskEditText = new EditText(MainActivity.this);
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try{
mHelper = new TaskDbHelper(MainActivity.this);
String task = String.valueOf(taskEditText.getText());
mHelper.adddata(MainActivity.this, task);
//incompleteTasks.addTask(mHelper.getAddedTask("0").get(0));
incompleteTasks.updateUI();
}
catch(Exception ex1){
Toast.makeText(MainActivity.this, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}catch (Exception ex) {
Log.d("MainActivity", "Exception: " + ex.getMessage());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
//Tab1 incompleteTasks = new Tab1();
incompleteTasks = new Tab1();
incompleteTasks.setContext(MainActivity.this);
return incompleteTasks;
case 1:
//Tab2 completedTasks = new Tab2();
completedTasks = new Tab2();
completedTasks.setContext(MainActivity.this);
return completedTasks ;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Incomplete";
case 1:
return "Completed";
}
return null;
}
}
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.TaskHolder> {
private ArrayList<Task> mTasks;
private boolean completedStatus;
private Context contextFromTab;
private int lastPosition = -1;
private RecyclerViewAnimator mAnimator;
//1
public class TaskHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private TextView mTask_id;
private TextView mTask_title;
private TextView mTask_created_date;
private ImageButton mImageButtonDone;
private ImageButton mImageButtonUndo;
private ImageButton mImageButtonEdit;
private ImageButton mImageButtonDelete;
//3
//private static final String PHOTO_KEY = "PHOTO";
//4
public TaskHolder(View v) {
super(v);
try{
//v.geti
mTask_id = v.findViewById(R.id.task_id);
mTask_title = v.findViewById(R.id.task_title);
mTask_created_date = v.findViewById(R.id.task_created_date);
mImageButtonDone = v.findViewById(R.id.imageButtonDone);
mImageButtonUndo = v.findViewById(R.id.imageButtonUndo);
mImageButtonEdit = v.findViewById(R.id.imageButtonEdit);
mImageButtonDelete = v.findViewById(R.id.imageButtonDelete);
v.setOnClickListener(this);
mImageButtonDone.setOnClickListener(this);
mImageButtonUndo.setOnClickListener(this);
mImageButtonEdit.setOnClickListener(this);
mImageButtonDelete.setOnClickListener(this);
//v.setAnimation();
}
catch (Exception ex){
Log.d("TaskHolder", ex.getMessage());
}
}
//5
#Override
public void onClick(View v) {
if(v.equals(mImageButtonDone)){
View parent = (View) v.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.changeTaskStatus(contextFromTab,true, _id);
removeAt(getAdapterPosition());
}
else if(v.equals(mImageButtonUndo)) {
View parent = (View) v.getParent();
TextView taskTextView = parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.changeTaskStatus(contextFromTab,false, _id);
}
else if(v.equals(mImageButtonEdit)) {
View parent = (View) v.getParent();
TextView taskIdTextView = (TextView) parent.findViewById(R.id.task_id);
TextView taskTitleTextView = (TextView) parent.findViewById(R.id.task_title);
final String _id = String.valueOf(taskIdTextView.getText());
String _title = String.valueOf(taskTitleTextView.getText());
/*Intent intent = new Intent(this, TaskDetails.class);
intent.putExtra("_id", _id);
intent.putExtra("_title", _title);
startActivity(intent);*/
try{
final EditText taskEditText = new EditText(contextFromTab);
taskEditText.setText(_title);
AlertDialog dialog = new AlertDialog.Builder(contextFromTab)
.setTitle("Edit task")
.setView(taskEditText)
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try{
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
String task = String.valueOf(taskEditText.getText());
mHelper.editTask(contextFromTab, task, _id);
updateAt(getAdapterPosition(), _id);
/*Tab1 tab1 = new Tab1();
tab1.setContext(MainActivity.this);
tab1.updateUI();*/
}
catch(Exception ex1){
Toast.makeText(contextFromTab, (String)ex1.getMessage(), Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}catch (Exception ex) {
Log.d("MainActivity", "Exception: " + ex.getMessage());
}
}
else if(v.equals(mImageButtonDelete)) {
View parent = (View) v.getParent();
TextView taskTextView = (TextView) parent.findViewById(R.id.task_id);
String _id = String.valueOf(taskTextView.getText());
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
mHelper.deleteTask(_id);
removeAt(getAdapterPosition());
}
Log.d("RecyclerView", "CLICK!");
}
public void bindTask(Task task, boolean completedStatus) {
try{
mTask_id.setText(Integer.toString(task._id) );
mTask_title.setText(task.title);
mTask_created_date.setText("created on: " + task.created_datetime);
if(completedStatus){
mImageButtonDone.setVisibility(View.INVISIBLE);
mImageButtonUndo.setVisibility(View.VISIBLE);
}else{
mImageButtonDone.setVisibility(View.VISIBLE);
mImageButtonUndo.setVisibility(View.INVISIBLE);
}
}
catch (Exception ex){
Log.d("bindTask", ex.getMessage());
}
}
public void addTask(Task task){
mTasks.add(0, task);
notifyItemInserted(0);
//smoothScrollToPosition(0);
}
public void removeAt(int position) {
mTasks.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount());
}
public void updateAt(int position, String task_id){
//mTasks.
//mTasks.set(position);
try{
TaskDbHelper mHelper = new TaskDbHelper(contextFromTab);
Task updatedTask = mHelper.getTaskById(task_id);
mTasks.set(position, updatedTask);
notifyItemChanged(position);
}
catch (Exception ex){
}
}
}
public RecyclerAdapter(ArrayList<Task> tasks, boolean tasksCompletedStatus, Context context, RecyclerView recyclerView) {
mTasks = tasks;
completedStatus = tasksCompletedStatus;
contextFromTab = context;
mAnimator = new RecyclerViewAnimator(recyclerView);
}
#Override
public RecyclerAdapter.TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
try{
View inflatedView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_todo, parent, false);
mAnimator.onCreateViewHolder(inflatedView);
return new TaskHolder(inflatedView);
}
catch(Exception ex){
Log.d("onCreateViewHolder", ex.getMessage());
return null;
}
}
private void setAnimation(View viewToAnimate, int position)
{
// If the bound view wasn't previously displayed on screen, it's animated
if (position > lastPosition)
{
Animation animation = AnimationUtils.loadAnimation(contextFromTab, android.R.anim.slide_in_left);
animation.setDuration(3000);
viewToAnimate.startAnimation(animation);
lastPosition = position;
}
}
#Override
public void onBindViewHolder(RecyclerAdapter.TaskHolder holder, int position) {
try{
Task itemTask = mTasks.get(position);
holder.bindTask(itemTask, completedStatus);
mAnimator.onBindViewHolder(holder.itemView, position);
}
catch(Exception ex){
Log.d("onBindViewHolder", ex.getMessage());
}
}
#Override
public int getItemCount() {
try{
return mTasks.size();
}
catch(Exception ex){
Log.d("getItemCount", ex.getMessage());
return 0;
}
}
public ArrayList<Task> getListTasks(){
return mTasks;
}
}
TaskDBHelper.java
public class TaskDbHelper extends SQLiteOpenHelper{
// Table Name
public static final String TABLE_NAME = "tasks";
// Table columns
public static final String _ID = "_id";
public static final String COL_TASK_TITLE = "title";
public static final String COL_TASK_PARENT_ID = "parent_id";
public static final String COL_TASK_COMPLETED_STATUS = "completed_status";
public static final String COL_TASK_CREATED_DATETIME = "created_datetime";
public static final String COL_TASK_MODIFIED_DATETIME = "modified_datetime";
// Database Information
static final String DB_NAME = "com.sagarmhatre.simpletodo";
// database version
static final int DB_VERSION = 1;
public TaskDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " +
_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_TASK_TITLE + " TEXT NOT NULL," +
COL_TASK_PARENT_ID + " INTEGER DEFAULT 0," +
COL_TASK_COMPLETED_STATUS + " BOOLEAN DEFAULT 0," +
COL_TASK_CREATED_DATETIME + " DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME'))," +
COL_TASK_MODIFIED_DATETIME + " DATETIME" +");";
db.execSQL(createTable);
}
catch (Exception ex){
Log.d("TaskDbHelper", "Exception: " + ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Insert Value
public void adddata(Context context,String task_title) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.insert(TABLE_NAME, null, values);
db.close();
}
public Task adddataWithReturnTask(Context context,String task_title) {
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.insert(TABLE_NAME, null, values);
db.close();
ArrayList<Task> taskList = this.getAddedTask("0");
return taskList.get(0);
}
catch(Exception ex){
Log.d("MainActivity", "Exception: " + ex.getMessage());
return null;
}
}
//Delete Query
public void deleteTask(String id) {
String deleteQuery = "DELETE FROM " + TABLE_NAME + " where " + _ID + "= " + id ;
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(deleteQuery);
}
public void changeTaskStatus(Context context,Boolean taskStatus, String id) {
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if(taskStatus)
values.put(COL_TASK_COMPLETED_STATUS, 1);
else
values.put(COL_TASK_COMPLETED_STATUS, 0);
db.update(TABLE_NAME, values, _ID + "=" + id, null);
db.close();
}
catch(Exception ex){
Log.d("changeTaskStatus() ", "Exception: " + ex.getMessage());
}
}
// Edit task - by me
public void editTask(Context context,String task_title, String id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_TASK_TITLE, task_title);
db.update(TABLE_NAME, values, _ID + "=" + id, null);
db.close();
}
//Get Row Count
public int getCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
if(cursor != null && !cursor.isClosed()){
count = cursor.getCount();
cursor.close();
}
return count;
}
//Get FavList
public ArrayList<Task> getTaskList(String ParentID, Boolean completedStatus){
try{
String selectQuery;
if(completedStatus){
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 1 + " ORDER BY " + _ID + " DESC";
}else{
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC";
}
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList;
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
public Task getTaskById(String _id){
try{
String selectQuery;
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ _ID + "="+_id;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList.get(0);
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
public ArrayList<Task> getAddedTask(String ParentID){
try{
String selectQuery;
selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE "+ COL_TASK_PARENT_ID + "="+ParentID+ " AND " + COL_TASK_COMPLETED_STATUS + " = " + 0 + " ORDER BY " + _ID + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<Task> TaskList = new ArrayList<Task>();
if (cursor.moveToFirst()) {
do {
Task task = new Task();
task._id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(_ID)));
task.title = cursor.getString(1);
task.parent_id = Integer.parseInt(cursor.getString(2));
task.completed_status = Boolean.parseBoolean(cursor .getString(3));
task.created_datetime = cursor.getString(4);
task.modified_datetime = cursor.getString(5);
TaskList.add(task);
} while (cursor.moveToNext());
}
return TaskList;
}
catch(Exception ex){
Log.d("getTaskList() ", "Exception: " + ex.getMessage());
return null;
}
}
}
Tab1.java
public class Tab1 extends Fragment {
private static final String TAG = "Tab1";
private TaskDbHelper mHelper;
//int listResourceID;
//ViewAdapter viewAdapter;
Context incompleteListContext;
Toolbar toolbar;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
RecyclerAdapter adapter;
public void setContext(Context context){
this.incompleteListContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mRecyclerView = rootView.findViewById(R.id.list_todo);
mRecyclerView.setHasFixedSize(true);
//mRecyclerView.setItemAnimator(new SlideInLeftAnimator());
//SlideInUpAnimator animator = new SlideInUpAnimator(new OvershootInterpolator());
//mRecyclerView.setItemAnimator(animator);
mLinearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLinearLayoutManager);
updateUI();
return rootView;
}
//#Override
//public void onViewCreated(View rootView, Bundle savedInstanceState){
//incompleteList = rootView.findViewById(R.id.list_todo_completed);
//updateUI();
//}
public void updateUI() {
try {
mHelper = new TaskDbHelper(incompleteListContext);
ArrayList<Task> taskList = mHelper.getTaskList("0",false);
adapter = new RecyclerAdapter(taskList, false, incompleteListContext, mRecyclerView);
mRecyclerView.setAdapter(adapter);
}
catch (Exception ex) {
Log.d(TAG, "Exception: " + ex.getMessage());
}
}
public RecyclerView getRecyclerView(){
return mRecyclerView;
}
}
So far I am successful in implementing delete and update operation without reloading the whole list in Tab1. But after adding an item I want to add it to the top and I am unable to do it as seen in most of RecyclerView tutorials. SO currently I reload the whole list (which I Know is not appropriate).
Need a way to not load whole list and add item at the top of list.
Being new to android development, any kind of help is welcome.
It's a bit hard to read Your code -> Please don't mix camelcase pascalcase prefix and non-prefix naming for variable.
For adding item on the top try with (PSEUDO CODE):
items.add(0, ITEM_HERE);
adapter.notifyDataSetChanged();
recyclerView.smoothScrollToPosition(0);
This addTask method not working like You want?
public void addTask(Task task){
mTasks.add(0, task);
notifyItemInserted(0);
smoothScrollToPosition(0);
}

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);

Categories

Resources