RecyclerView not refreshing after inserting item using Alertdialog - java

I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.
Problem:
(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.
My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].
but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.
Below is my All Code.
CategoryAdapter
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {
private ArrayList<CategoryModel> dataList;
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCategoryItem;
MyViewHolder(View view) {
super(view);
tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
}
}
CategoryAdapter(ArrayList<CategoryModel> dataSet) {
this.dataList = dataSet;
this.filterList = dataSet;
}
// I used this method too. but same problem.
void refreshAdapter(ArrayList<CategoryModel> dataSet) {
dataList.clear();
dataList.addAll(dataSet);
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_row_category_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
CategoryModel categoryModel = dataList.get(position);
holder.tvCategoryItem.setText(categoryModel.getCategoryName());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
CategoryListActivity
MyDatabase myDb;
CategoryModel categoryModel;
RecyclerView recyclerCategory;
RecyclerView.LayoutManager layoutManager;
CategoryAdapter adapter;
ArrayList<CategoryModel> allCategory;
int CategoryType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
new RecyclerItemClickListener.OnItemTouchListener() {
#Override
public void onItemClick(View view, int position) {
TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
String CategoryName = tvCategoryItem.getText().toString();
Intent intent = new Intent();
CategoryId = allCategory.get(+position).getCategoryId();
intent.putExtra("CategoryId", String.valueOf(CategoryId));
Log.e("Clicked Cat Id is ", "" + CategoryId);
intent.putExtra("CategoryName", CategoryName);
setResult(Activity.RESULT_OK, intent);
finish();
}
#Override
public void onLongItemClick(View view, int position) {
}
}
));
}
private void openAlert() {
final EditText etCategoryName = new EditText(this);
CustomAlertDialog dialog1 = new CustomAlertDialog(this);
dialog1.setTitle("Add Category");
dialog1.setView(etCategoryName);
dialog1.setCancelable(true);
dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String CategoryName = etCategoryName.getText().toString().trim();
final String storedCategoryName = myDb.ExistCategory(CategoryName);
if (CategoryName.equals("") && CategoryName.length() == 0) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
if (CategoryName.equals(storedCategoryName)) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
dialogInterface.dismiss();
categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));
myDb.createCategory(categoryModel);
Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
+ "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();
allCategory.clear();
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChanged();
}
}
}
});
dialog1.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
openAlert();
default:
return super.onOptionsItemSelected(item);
}
}
}
my createCategory() method.
public long createCategory(CategoryModel categoryModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CATEGORY_NAME, categoryModel.getCategoryName());
values.put(CATEGORY_TYPE, categoryModel.getCategoryType());
long CategoryId = db.insert(TABLE_CATEGORY, null, values);
db.close();
return CategoryId;
}
and Finally my getCategoryByType() method on My Database.
public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
ArrayList<CategoryModel> Categories = new ArrayList<>();
// String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
Log.e(DB_LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
CategoryModel categoryModel = new CategoryModel();
categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));
Categories.add(categoryModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return Categories;
}
Any Type of Help, Suggestion is much Appreciated.....Thanks in advance
Below is Screenshot after adding First Item.
First Item Inserted but not shown in RecycleView
My LogCat Screenshot is below.
Logcat Screenshot

change your onCreate in this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
}
and now you can use adapter.notifyDataSetChanged(); without recreation of adapter and set them to RecyclerView
if you make in setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); then your reference to allCategory is lost.
you need instead
allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));

Change your Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = new ArrayList<>();
adapter = new CategoryAdapter(allCategory);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.setAdapter(adapter);
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChange();
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
}
and inside setPositiveButton, replace
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
with
adapter.notifyDataSetChanged();
Also replace
allCategory = myDb.getCategoryByType(CategoryType);
with
allCategory.addAll(myDb.getCategoryByType(CategoryType));
And try to run your program again.

Related

Trying to get position of lists throws "java.lang.IndexOutOfBoundsException"

I have two array lists, one for employees, another for their availabilities. The arrays are of different size. I don't see the problem with that when I'm using the array of the larger size in getItemCount():
#Override
public int getItemCount() {
return allEmployees.size();
}
I set recycler view to get all employee items, however my availability is a shorter list. If I have 6 availability's and 12 employees everything goes smooth on the first page as it only shows the 6 employees. But when I scroll down it will crash as there is a 7th employee but no 7th availability.
Recycler View :
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.MyViewHolder> {
List<EmployeeModel> allEmployees;
List<AvailabilityModel> allAvailabilitys;
Context context;
public RecycleViewAdapter(List<EmployeeModel> allEmployees, List<AvailabilityModel> allAvailabilitys, Context context) {
this.allAvailabilitys = allAvailabilitys;
this.allEmployees = allEmployees;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_employee, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
AvailabilityModel available = allAvailabilitys.get(position);
EmployeeModel employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
//holder.position = position;
holder.employee = employee;
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditEmployee.class);
intent.putExtra("Editing", employee);
context.startActivity(intent);
}
});
holder.availabilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, availability_screen_code.class);
intent.putExtra("Available", employee);
intent.putExtra("Days", available);
context.startActivity(intent);
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ViewEmployee.class);
intent.putExtra("Viewing", employee);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return allEmployees.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView firstName;
TextView lastName;
TextView employeeID;
int position;
ImageButton editButton;
ImageButton availabilityButton;
EmployeeModel employee;
ConstraintLayout parentLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
firstName = itemView.findViewById(R.id.fNameView);
lastName = itemView.findViewById(R.id.lNameView);
employeeID = itemView.findViewById(R.id.eIDView);
editButton = itemView.findViewById(R.id.imageButton2);
availabilityButton = itemView.findViewById(R.id.imageButton4);
parentLayout = itemView.findViewById(R.id.parentLayout);
}
}
}
Where I'm using the position:
public class availability_screen_code extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner mondaySpinner, tuesdaySpinner, wednesdaySpinner, thursdaySpinner, fridaySpinner, saturdaySpinner, sundaySpinner;
// private String mondayChoice, tuesdayChoice, wednesdayChoice, thursdayChoice, fridayChoice, saturdayChoice, sundayChoice;
// private static final boolean [] choices = new boolean[6];
private ImageButton confirmation;
EmployeeDBAssist employeeDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.availability_screen);
mondaySpinner = findViewById(R.id.mondaySpinner);
tuesdaySpinner = findViewById(R.id.tuesdaySpinner);
wednesdaySpinner = findViewById(R.id.wednesdaySpinner);
thursdaySpinner = findViewById(R.id.thursdaySpinner);
fridaySpinner = findViewById(R.id.fridaySpinner);
saturdaySpinner = findViewById(R.id.saturdaySpinner);
sundaySpinner = findViewById(R.id.sundaySpinner);
confirmation = findViewById(R.id.confirm);
//this is linked to the recycler which gets an entire list of availability!
Bundle bundle = getIntent().getExtras();
AvailabilityModel available = (AvailabilityModel) getIntent().getSerializableExtra("Days");
EmployeeModel employee = (EmployeeModel) getIntent().getSerializableExtra("Available"); //this is where im using it
employeeDB = new EmployeeDBAssist(availability_screen_code.this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.availableTimes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//monday
mondaySpinner.setAdapter(adapter);
mondaySpinner.setOnItemSelectedListener(this);
String availableString = available.getMonday();
mondaySpinner.setSelection(getIndex(mondaySpinner, availableString));
Toast.makeText(this, availableString, Toast.LENGTH_SHORT).show();
//tuesday
tuesdaySpinner.setAdapter(adapter);
tuesdaySpinner.setOnItemSelectedListener(this);
//wednesday
wednesdaySpinner.setAdapter(adapter);
wednesdaySpinner.setOnItemSelectedListener(this);
//thursday
thursdaySpinner.setAdapter(adapter);
thursdaySpinner.setOnItemSelectedListener(this);
//friday
fridaySpinner.setAdapter(adapter);
fridaySpinner.setOnItemSelectedListener(this);
//saturday
saturdaySpinner.setAdapter(adapter);
saturdaySpinner.setOnItemSelectedListener(this);
//sunday
sundaySpinner.setAdapter(adapter);
sundaySpinner.setOnItemSelectedListener(this);
confirmation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AvailabilityModel availabilityModel;
try{
availabilityModel = new AvailabilityModel(-1, employee.getEID(), mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
EmployeeDBAssist employeeDBAssist = new EmployeeDBAssist(availability_screen_code.this);
employeeDBAssist.updateAvailability(employee.getEID(),mondaySpinner.getSelectedItem().toString(), tuesdaySpinner.getSelectedItem().toString(), wednesdaySpinner.getSelectedItem().toString(), thursdaySpinner.getSelectedItem().toString(), fridaySpinner.getSelectedItem().toString(), saturdaySpinner.getSelectedItem().toString(), sundaySpinner.getSelectedItem().toString());
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
boolean success = employeeDBAssist.addAvailability(availabilityModel);
}
catch (Exception e){
Toast.makeText(availability_screen_code.this, "Error Setting Availability", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(availability_screen_code.this,activity_main_code.class);
startActivity(i);
Toast.makeText(availability_screen_code.this, String.valueOf(employee.getEID()) + " " + mondaySpinner.getSelectedItem().toString()+ " " + tuesdaySpinner.getSelectedItem().toString()+ " " + wednesdaySpinner.getSelectedItem().toString()+ " " + thursdaySpinner.getSelectedItem().toString()+ " " + fridaySpinner.getSelectedItem().toString()+ " " + saturdaySpinner.getSelectedItem().toString()+ " " + sundaySpinner.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
}
});
}
availability table has 2 values and employees 7. In getItemCount I'm using the size of my employee table. However, I need to get the position of my availability so that I can use it in another class. It will only work for the first two entries. Once I scroll down it throws :
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
Adding an availability for every employee would defeat the purpose of my project. How to solve this with the use of two separate arrays of different size?
You can check whether the corresponding AvailabilityModel exists before calling List#get(), if not, directly assign available to null. At the same time, you also need to perform a null check in intent.putExtra("Available", employee);.
Update I fixed the problem using a little bit of what #perfect puzzle said here's the solution
Here's the recyclerViewAdapter updated code
I first created an if statement to check whether the pointer was below the size of the availability list allAvailabilitys.size(), then created a null check within the intent.putExtra field as per #perfectpuzzle instruction
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
EmployeeModel employee;
AvailabilityModel available = null;
if(position < allAvailabilitys.size()){
available = allAvailabilitys.get(position);
employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
holder.employee = employee;
} else{
employee = allEmployees.get(position);
holder.employeeID.setText(String.valueOf(allEmployees.get(position).getEID()));
holder.firstName.setText(allEmployees.get(position).getfName());
holder.lastName.setText(allEmployees.get(position).getlName());
holder.employee = employee;
}
EmployeeModel finalEmployee = employee;
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, EditEmployee.class);
intent.putExtra("Editing", finalEmployee);
context.startActivity(intent);
}
});
EmployeeModel finalEmployee1 = employee;
AvailabilityModel finalAvailable = available;
holder.availabilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, availability_screen_code.class);
intent.putExtra("Available", finalEmployee1);
if(finalAvailable!= null){
intent.putExtra("Days", finalAvailable);
}
context.startActivity(intent);
}
});
EmployeeModel finalEmployee2 = employee;
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ViewEmployee.class);
intent.putExtra("Viewing", finalEmployee2);
context.startActivity(intent);
}
});
}
}
Updated use of position
here I also check if available is null and I also created a function to translate a null into the default String used in my spinner.
Bundle bundle = getIntent().getExtras();
AvailabilityModel available = (AvailabilityModel) getIntent().getSerializableExtra("Days");
EmployeeModel employee = (EmployeeModel) getIntent().getSerializableExtra("Available");
employeeDB = new EmployeeDBAssist(availability_screen_code.this);
//setting elements in spinner
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.availableTimes, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//monday
mondaySpinner.setAdapter(adapter);
//tuesday
tuesdaySpinner.setAdapter(adapter);
//wednesday
wednesdaySpinner.setAdapter(adapter);
//thursday
thursdaySpinner.setAdapter(adapter);
//friday
fridaySpinner.setAdapter(adapter);
//saturday
saturdaySpinner.setAdapter(adapter);
//sunday
sundaySpinner.setAdapter(adapter);
if(available != null){
mondayChoice = getAvailableDay(available.getMonday());
mondaySpinner.setSelection(getIndex(mondaySpinner, mondayChoice));
tuesdayChoice = getAvailableDay(available.getTuesday());
tuesdaySpinner.setSelection(getIndex(tuesdaySpinner, tuesdayChoice));
wednesdayChoice = getAvailableDay(available.getWednesday());
wednesdaySpinner.setSelection(getIndex(wednesdaySpinner, wednesdayChoice));
thursdayChoice = getAvailableDay(available.getThursday());
thursdaySpinner.setSelection(getIndex(thursdaySpinner, thursdayChoice));
fridayChoice = getAvailableDay(available.getFriday());
fridaySpinner.setSelection(getIndex(fridaySpinner, fridayChoice));
saturdayChoice = getAvailableDay(available.getSaturday());
saturdaySpinner.setSelection(getIndex(saturdaySpinner, saturdayChoice));
sundayChoice = getAvailableDay(available.getSunday());
sundaySpinner.setSelection(getIndex(sundaySpinner, sundayChoice));
}
else{
Toast.makeText(this, "null field", Toast.LENGTH_SHORT).show();
}
}
Hope this can help someone out.

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. ***

how to put a few data into array variable and post as JSONarray?

I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.

Database refusing to delete item

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.

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

Categories

Resources