Adding item in RecyclerView Fragment [closed] - java

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

Related

SQL Lite Data not being inserted (Android Studio in java)

I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!

Why my bookmarked words doesn't saved to sqlite database if i want to add them from another fragment?

The main problem is that when i add bookmark codes from direct recyclerview it works perfectly fine but when i add those codes to another fragment it just only show a toast that bookmark is added or deleted but that bookmarked word doesn't show in favorite list.
Here is my Database codes
public class DictionaryDB {
public static final String ID = "id";
public static final String SANSKRIT = "sanskrit_word";
public static final String BANGLA = "bn_word";
public static final String STATUS = "status";
public static final String USER = "user_created";
public static final String TABLE_NAME = "sanskrit_words";
public static final String BOOKMARKED = "b";
public static final String USER_CREATED = "u";
DatabaseInitializer initializer;
public DictionaryDB(DatabaseInitializer initializer) {
this.initializer = initializer;
}
public void addWord(String sanskritWord, String banglaWord) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "INSERT INTO " + TABLE_NAME + " (" + SANSKRIT +
", " + BANGLA + ", " + USER + ") VALUES ('" + sanskritWord +
"', '" + banglaWord + "', '" + USER_CREATED + "') ";
db.execSQL(sql);
}
public List<Word> getWords(String sanskritWord) {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + SANSKRIT + " LIKE ? ";
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{sanskritWord + "%"});
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
//************Waka Maka Saka *****************//******************//
public List<Word> getBookmarkedWords() {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + STATUS + " = '" + BOOKMARKED + "'";
Cursor cursor = db.rawQuery(sql, null);
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
cursor.close();
db.close();
return wordList;
}
public void bookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '"
+ BOOKMARKED + "' WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
public void deleteBookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '' " +
" WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
}
My RecyclerView codes
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>implements Filterable {
private Context context;
private List<Word> wordList;
List<Word> filwordList;
private DictionaryDB dictionaryDB;
public RecyclerViewAdapter(Context context, List<Word> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Word>(itemList);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
// Create and return a new holder instance
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Word word = wordList.get(position);
holder.msanskrit.setText(word.sanskrit);
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
}
else {
holder.bookmark.setImageResource(R.drawable.cards_heart_grey);
}
holder.bookmark.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, holder.bookmark);
}
});
}
private void bookMarkWord(final Word word, final ImageButton bookmark) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
bookmark.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(context, "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
bookmark.setImageResource(R.drawable.cards_heart);
Toast.makeText(context, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}
/*
public void updateEntries(List<Word> wordList) {
if (wordList == null) {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Sorry!")
.setMessage("Your phone doesn't support pre-built database")
.create();
dialog.show();
} else {
this.wordList = wordList;
notifyDataSetChanged();
}
}
*/
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Word> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Word item : filwordList) {
if (item.getSanskrit().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Word>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView msanskrit;
final ImageButton bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
msanskrit = itemView.findViewById(R.id.tvSansTerm);
// mbangla = itemView.findViewById(R.id.tvBnTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
#Override
public void onClick(View view) {
int position = this.getAdapterPosition();
Word word = wordList.get(position);
String sanskrit = word.getSanskrit();
String bangla = word.getBangla();
// String sources = term.getMSources();
Intent intent = new Intent(context, TermThreeDetailsActivity.class);
intent.putExtra("Rsanskrit", sanskrit);
intent.putExtra("Rbangla", bangla);
// intent.putExtra("Rsources", sources);
context.startActivity(intent);
}
}
}
My Detalis Fragment codes
public class TermThreeDetailsFragment extends Fragment {
private Toolbar toolbar;
TextView termTextView,descTextView;
private ImageButton imgBtn;
private DictionaryDB dictionaryDB;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
termTextView = view.findViewById(R.id.textvWord);
descTextView = view.findViewById(R.id.textvDesc);
imgBtn = view.findViewById(R.id.favAddBtn);
getData();
toolbar = ((Toolbar) view.findViewById(R.id.toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
WordCheck();
return view;
}
public void getData() {
Intent intent = getActivity().getIntent();
String sanskrit = intent.getStringExtra("Rsanskrit");
String bangla = intent.getStringExtra("Rbangla");
termTextView.setText(sanskrit);
descTextView.setText(bangla);
}
private void WordCheck() {
final Word word = new Word();
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
imgBtn.setImageResource(R.drawable.cards_heart);
}
else {
imgBtn.setImageResource(R.drawable.cards_heart_grey);
}
imgBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, imgBtn);
}
});
}
private void bookMarkWord(final Word word, final ImageButton imgBtn) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
imgBtn.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(getContext(), "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
imgBtn.setImageResource(R.drawable.cards_heart);
Toast.makeText(getContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}}
My Favorite Fragment codes
public class FavoritesFragment extends Fragment {
RecyclerView rv;
private LinearLayoutManager layoutManager;
DictionaryDB dictionaryDB;
FavoriteAdapter rvFavAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.favorites_fragment,container,false);
Toolbar toolbar = ((Toolbar) view.findViewById(R.id.fav_toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
List<Word> wordList = dictionaryDB.getBookmarkedWords();
rv = ((RecyclerView) view.findViewById(R.id.rvFavorites));
if (wordList.size() != 0) {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
rvFavAdapter = new FavoriteAdapter(getContext(), dictionaryDB,wordList);
rv.setAdapter(rvFavAdapter);
} else {
Toast.makeText(getContext(), "You have no bookmark yet.", Toast.LENGTH_SHORT).show();
}
return view;
}
}
When i use bookmark codes from direct RecyclerView
When i use same bookmark codes from another fragment this happens
Any help will be heavily appreciated 🙏
Problem Solved
Just add those to RecyclerView
int position = this.getAdapterPosition();
Word word = wordList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
And add this codes to Fragment Class
word = new Word(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
termTextView.setText(word.getSanskrit());
descTextView.setText(word.getBangla());
}
*** You need to make you POJO class Parcelable to pass objects between fragments. ***

Data wont insert and display on my app | Android Studio

My app isn't displaying the data i'm inserting into the interface, i'm creating a fighter database where my coach can add fighters from the gym into it. I'm using a card view and recycling adaptor to display all the data but when I click submit it wont display.
Error log:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<Item>list = new ArrayList<Item>();
private ItemAdapter adapter;
private RecyclerView recyclerView;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fetchRecords();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getLayoutInflater();
View mView1 = inflater.inflate(R.layout.activity_add,null);
final EditText input_name = (EditText) mView1.findViewById(R.id.Name);
final EditText input_age = (EditText) mView1.findViewById(R.id.Age);
final EditText input_weight = (EditText) mView1.findViewById(R.id.Weight);
final EditText input_height = (EditText) mView1.findViewById(R.id.Height);
final EditText input_reach = (EditText) mView1.findViewById(R.id.Reach);
final Button btnSave = (Button) mView1.findViewById(R.id.btnSave);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(mView1).setTitle("Add new Record")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialog.dismiss();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = input_name.getText().toString();
String age = input_age.getText().toString();
String weight = input_weight.getText().toString();
String height = input_height.getText().toString();
String reach = input_reach.getText().toString();
if (name.equals("") && age.equals("") && weight.equals("") && height.equals("")&& reach.equals("")){
Snackbar.make(view,"Field incomplete",Snackbar.LENGTH_SHORT).show();
}else {
Save(name,age,name,height,reach);
dialog.dismiss();
Snackbar.make(view,"Saving",Snackbar.LENGTH_SHORT).show();
}
}
});
dialog = builder.create();
dialog.show();
}
});
}
public void fetchRecords() {
recyclerView = (RecyclerView) findViewById(R.id.recycler);
adapter = new ItemAdapter(this,list);
LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
list.clear();
Functions functions = new Functions(MainActivity.this);
ArrayList<Item>data = functions.getAllRecords();
if (data.size()>0){
for (int i = 0; i<data.size(); i++){
int id = data.get(i).getId();
String namel = data.get(i).getName();
String agel = data.get(i).getAge();
String weightl = data.get(i).getWeight();
String heightl = data.get(i).getHeight();
String reachl = data.get(i).getReach();
Item item = new Item();
item.setId(id);
item.setName(namel);
item.setAge(agel);
item.setWeight(weightl);
item.setHeight(heightl);
item.setReach(reachl);
list.add(item);
}adapter.notifyDataSetChanged();
}else {
Toast.makeText(MainActivity.this, "No Records found.", Toast.LENGTH_SHORT).show();
}
}
private void Save(String name, String age, String weight, String height, String reach) {
Functions functions = new Functions(MainActivity.this);
Item item = new Item();
item.setName(name);
item.setAge(age);
item.setWeight(weight);
item.setHeight(height);
item.setReach(reach);
functions.Insert(item);
Toast.makeText(MainActivity.this, "Saved...", Toast.LENGTH_SHORT).show();
fetchRecords();
}
#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;
}
}
public class Functions extends SQLiteOpenHelper {
private static final String DB_NAME = "crud.db";
private static final int DB_VERSION = 1;
private Fighter fighter = new Fighter();
public Functions(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(fighter.CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + fighter.TABLE_FIGHTER);
}
public void Insert(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.ID,item.getId());
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.insert(fighter.TABLE_FIGHTER,null,contentValues);
}
public ArrayList<Item>getAllRecords(){
ArrayList<Item>list = new ArrayList<Item>();
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER;
Cursor cursor = database.rawQuery(sql,null);
if (cursor.moveToFirst()){
do {
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(5));
list.add(item);
}while (cursor.moveToNext());
}
cursor.close();
database.close();
return list;
}
public Item getSingleItem(int id){
SQLiteDatabase database = getReadableDatabase();
String sql = "SELECT * FROM " + fighter.TABLE_FIGHTER + " WHERE " + fighter.ID + "=?";
Cursor cursor = database.rawQuery(sql,new String[]{String.valueOf(id)});
if (cursor != null)
cursor.moveToNext();
Item item = new Item();
item.setId(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setAge(cursor.getString(2));
item.setWeight(cursor.getString(3));
item.setHeight(cursor.getString(4));
item.setReach(cursor.getString(4));
cursor.close();
database.close();
return item;
}
public void DeleteItem(int id){
SQLiteDatabase database = getWritableDatabase();
database.delete(fighter.TABLE_FIGHTER,fighter.ID + "=?",new String[]{String.valueOf(id)});
database.close();
}
public void Update(Item item){
SQLiteDatabase database = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(fighter.NAME,item.getName());
contentValues.put(fighter.AGE,item.getAge());
contentValues.put(fighter.WEIGHT,item.getWeight());
contentValues.put(fighter.HEIGHT,item.getHeight());
contentValues.put(fighter.REACH,item.getReach());
database.update(fighter.TABLE_FIGHTER,contentValues,fighter.ID + "=?",new String[]{String.valueOf(item.getId())});
}
}
public class Fighter {
public static final String TABLE_FIGHTER = "fighter";
public static final String ID = "ID";
public static final String NAME = "Name";
public static final String AGE = "Age";
public static final String WEIGHT = "Weight";
public static final String HEIGHT = "Height";
public static final String REACH = "Reach";
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT"
+ REACH + " TEXT"+ ")";
}
According to your code, you have missed a comma after + HEIGHT + " TEXT" . therefore table is not created properly due to SQL syntax errors. please try with following. i have added the comma for you.
public static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_FIGHTER + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ AGE + " TEXT,"
+ WEIGHT + " TEXT,"
+ HEIGHT + " TEXT,"
+ REACH + " TEXT"+ ")";

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

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