List refreshed withous notifyDataSetChange? - android

I have a little question for you. I have an app which displays a list of subjects which could be removed or addedd. During developing I realized that I could add new subject without call notifyDataSetChange, why?
Class (ListSubject) which manage list of subjects:
public static ListView mListView;
private Context mContext;
List<Subject> data;
SubjectAdapter subjectSubjectAdapter;
public ListSubject(Context mContext) {
this.mContext = mContext;
}
public List<Subject> populateList() {
DBManager db = new DBManager(mContext);
data = db.GetSubjects();
return data;
}
public void DeleteAll(){
DBManager db = new DBManager(mContext);
db.ClearTable("TBLSUBJECTS");
data.clear();
}
public void AddSubject(String name, int frequency){
DBManager db = new DBManager(mContext);
Subject subToAdd = db.InsertSubject(name, frequency);
data.add(subToAdd);
}
public void DeleteSubject(int id){
DBManager db = new DBManager(mContext);
db.DeleteSubject(id);
}
}
Class (ListSubjectActivity) which rappresents the activity where is listview:
DBManager db;
Button btnClearSubjectTable;
Button btnAddSub;
Context mContext;
private List<Subject> mListSubject;
private SubjectAdapter subjectAdapter;
private ListView lvSubject;
private ListSubject ls;
public ListSubjectActivity(Context mContext) {
this.mContext = mContext;
}
public ListSubjectActivity(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_subject);
db = new DBManager(this);
btnClearSubjectTable = (Button) findViewById(R.id.btnClearSubjectTable);
btnAddSub = (Button) findViewById(R.id.btnAddSubject);
lvSubject = (ListView)findViewById(R.id.subjectList);
mListSubject = new ArrayList<>();
ls = new ListSubject(getApplicationContext());
mListSubject = ls.populateList();
btnClearSubjectTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteAll();
subjectAdapter.notifyDataSetChanged();
}
});
btnAddSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(ListSubjectActivity.this);
dialog.setContentView(R.layout.dialog_insert_subject);
final EditText txtNewSubName = (EditText) dialog.findViewById(R.id.txtNewSubName);
final EditText txtFreqNewSub = (EditText) dialog.findViewById(R.id.txtFreqNewSub);
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.btnCancel);
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, 700);
}
});
subjectAdapter = new SubjectAdapter(getApplicationContext(), mListSubject);
lvSubject.setAdapter(subjectAdapter);
}
public void AddSubject(String newSub, int frequency)
{
ls.AddSubject(newSub, frequency);
}
My subject adapter:
private Context mContext;
private List<Subject> mList;
private ListSubject ls;
public SubjectAdapter(Context mContext, List<Subject> mList) {
this.mContext = mContext;
this.mList = mList;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_subject_list,null);
TextView txtSubjectName = v.findViewById(R.id.txtName);
TextView txtFrequency = v.findViewById(R.id.txtFrequency);
txtSubjectName.setText(mList.get(position).GetSubjectName());
txtFrequency.setText(Integer.toString(mList.get(position).GetFrequency()));
ls = new ListSubject(mContext);
ImageButton btnDeleteSub = (ImageButton) v.findViewById(R.id.btnDeleteSub);
btnDeleteSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteSubject(mList.get(position).GetSubjectID());
mList.remove(position);
notifyDataSetChanged(); useless
}
});
return v;
}
}
Keep in mind please, that I'm new in android development so could be make a lot of mistake. Thank you who help me

If your current code is what you're wondering about, you are calling notifyDataSetChanged() when adding an item. It's right here:
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged(); //see?
dialog.dismiss();
}
});

Related

How to check if an item already exists in a Room Database?

I have this adapter with a button that dependent on if a object already exists in my Room Database or not will have a differente behavior when it´s clicked. Basically what I want to do is if the object exists I want to remove it. In case it doesn´t I want to add it to my database. I created this method in Dao and a Task to check the existence. Since the Task is asynchronous ,how can I do the verification?
My Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.RestaurantViewHolder> {
private Context mContext;
private List<Restaurant_> mRestaurants;
private Activity act;
private FirebaseAuth mAuth;
private String currentUserId;
private View rView;
public RestaurantAdapter(Context context, List<Restaurant_> restaurants, Activity activity) {
mRestaurants = restaurants;
mContext = context;
act = activity;
}
#Override
public RestaurantViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Get layout inflater from context
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate layout
rView = inflater.inflate(R.layout.item_restaurant, parent, false);
// Return a new holder instance
return new RestaurantViewHolder(rView);
}
#Override
public void onBindViewHolder(RestaurantViewHolder viewHolder, final int position) {
// Get the data model based on position
final Activity activity = act;
final Restaurant_ restaurant = mRestaurants.get(position);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
final TextView name = viewHolder.nameTextView;
name.setText(restaurant.getName());
final TextView rating = viewHolder.ratingTextView;
rating.setText((restaurant.getUserRating().getAggregateRating()));
final TextView distance = viewHolder.distanceTextView;
distance.setText(String.valueOf(restaurant.getDistance()) + " Km");
final ImageButton addToWishlistButton = viewHolder.addToWishlistButton;
addToWishlistButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Wishlist wishlist = new Wishlist(currentUserId, restaurant.getId());
//if(alreadyExists){
//RemoveWLTask rlt=new RemoveWLTask(wishlist,activity);
//rlt.execute()
// }
// else{
AddWLTask wlt = new AddWLTask(wishlist, activity);
wlt.execute();
//}
}
});
final ImageButton addToFavoritesButton = viewHolder.addToFavoritesButton;
addToFavoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToFavoritesButton.getBackground().setTint(activity.getResources().getColor(R.color.red));
addToFavorites();
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LiveFragment.getListener().onRestaurantClicked(restaurant.getId());
}
});
}
#Override
public int getItemCount() {
return mRestaurants.size();
}
public class RestaurantViewHolder extends RecyclerView.ViewHolder {
public TextView nameTextView;
public TextView ratingTextView;
public TextView distanceTextView;
public ImageButton addToWishlistButton;
public ImageButton addToFavoritesButton;
public RestaurantViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.restaurantName);
ratingTextView = itemView.findViewById(R.id.restaurantRating);
distanceTextView = itemView.findViewById(R.id.restaurantDistance);
addToWishlistButton = itemView.findViewById(R.id.button_wishlist);
addToFavoritesButton = itemView.findViewById(R.id.button_favorites);
}
}
}
My DAO
#Dao
public interface DAO {
#Insert
public void addToWishlist(Wishlist wishlist);
#Delete
public void deleteFromWishlist(Wishlist wishlist);
#Query("Select restaurantId From wishlist Where userId=:id")
public String[] loadWishlist(String id);
#Query("Select restaurantId From wishlist where userId=:userID AND restaurantId=:restaurantID")
public String[]checkExists(String userID, String restaurantID);
}
##My Task ##
public class CheckWLTask extends AsyncTask<Void, Void, Void> {
private DB db;
private Activity activity;
private String userId;
private String restaurantId;
private String [] response;
public CheckWLTask(Activity activity, String idUser, String idRestaurant) {
this.activity = activity;
this.userId = idUser;
this.restaurantId = idRestaurant;
db = Room.databaseBuilder(activity.getApplicationContext(), DB.class, "sample-db").build();
}
#Override
protected Void doInBackground(Void... voids) {
while (!isCancelled()) {
this.response=db.daoAcess().checkExists(userId,restaurantId);
break;
}
return null;
}
}
``

How to fetch data from another classes via Adapter in Android

Here I'm trying to make a quiz application without using databases (requirement). Each question has 4 options.
I had made a class for Questions. Now, in the activity in which I want to show my data, I'm unable to get method to fetch the data from the QuestionModelClass.
I had made 2D Array but it gets more complicated to get it. Is there any way to bind 3 of the classes (QuestionModelClass, Adapter class, and Activity class)?
public class QuestionsModelClass {
private String sQuestion;
private String sRightAnswer;
private List<String> sOptions;
QuestionsModelClass(){
sQuestion = null;
sRightAnswer = null;
sOptions = null;
}
public QuestionsModelClass(String sQuestion, String sRightAnswer, List<String> sOptions) {
this.sQuestion = sQuestion;
this.sRightAnswer = sRightAnswer;
this.sOptions = sOptions;
}
public String getsQuestion() {
return sQuestion;
}
public void setsQuestion(String sQuestion) {
this.sQuestion = sQuestion;
}
public String getsRightAnswer() {
return sRightAnswer;
}
public void setsRightAnswer(String sRightAnswer) {
this.sRightAnswer = sRightAnswer;
}
public List<String> getsOptions() {
return sOptions;
}
public void setsOptions(List<String> sOptions) {
this.sOptions = sOptions;
}
}
And my Adapter Class
public class QuizAdapter extends BaseAdapter {
private Context context;
private List<QuestionsModelClass> questionClassList;
private String[][] options;
private LayoutInflater inflater;
private QuizAdapter(Context c, List<QuestionsModelClass> l){
this.context= c;
this.questionClassList = l;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return questionClassList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.questionpattern, parent,false);
QuestionsModelClass questions = questionClassList.get(position);
TextView quesText= convertView.findViewById(R.id.questionTextView);
RadioButton radioButtonA = convertView.findViewById(R.id.optionA);
RadioButton radioButtonB = convertView.findViewById(R.id.optionB);
RadioButton radioButtonC = convertView.findViewById(R.id.optionC);
RadioButton radioButtonD = convertView.findViewById(R.id.optionD);
return convertView;
}
And this is the Activity class in which I am trying to implement all the functions
public class QuizActivity extends Activity {
final Context context= this;
private List<QuestionsModelClass> classObject;
Button okayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
String[] question= new String[]{"Q1. ABDE", "Q2. ADDASD"};
String[][] op;
String[] right = new String[]{"abc","def"};
classObject = new ArrayList<>();
op= new String[][]{
{"a1", "2", "3", "4"},
{"b1","b2","b3","b4"}};
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.customdialoguebox);
dialog.show();
okayButton = (Button) dialog.findViewById(R.id.okayButton);
okayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,"Good Luck!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}

To pass only incremented value to listview on nextpage

I am able to send data on listview in nextpage.But problem is that items with quantity 0 is also passed.I want to show items whose quantity is incremented and not all items present in listview.Here is my code-
MainActivity.java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener{
Button show;
ListView list_item;
ArrayList<Items> itemsArrayList;
SearchView searchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
intent.putExtra("data", itemsArrayList);
startActivity(intent);
}
});
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
}
public void setupSearchView()
{
searchview.setOnQueryTextListener(this);
searchview.setQueryHint("Search Here");
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)) {
list_item.clearTextFilter();
} else {
list_item.setFilterText(s);
}
return true;
}
}
Custom.java
public class Custom extends BaseAdapter implements Filterable{
Activity a;
ArrayList<Items> itemsArrayList;
ArrayList<Items> filtered;
public Custom(Activity a, ArrayList<Items> itemsArrayList) {
this.a = a;
this.itemsArrayList = itemsArrayList;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int i) {
return itemsArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results=new FilterResults();
ArrayList<Items> data=new ArrayList<Items>();
if (filtered==null)
filtered=itemsArrayList;
if (filtered != null && filtered.size() > 0) {
for (final Items g : filtered) {
if (g.getItemname().toLowerCase()
.contains(charSequence.toString()))
data.add(g);
}
results.values=data;
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
itemsArrayList=(ArrayList<Items>)filterResults.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public class Holder{
TextView sr,item,qty,price,pl,min,rate;
}
#Override
public View getView(final int position, final View view, ViewGroup viewGroup) {
final Holder holder=new Holder();
LayoutInflater li=a.getLayoutInflater();
final View view1=li.inflate(R.layout.customlist,viewGroup,false);
holder.sr=(TextView)view1.findViewById(R.id.s_no);
holder.item=(TextView)view1.findViewById(R.id.i_name);
holder.qty=(TextView)view1.findViewById(R.id.qty);
holder.price=(TextView)view1.findViewById(R.id.pr);
holder.rate=(TextView)view1.findViewById(R.id.frate);
holder.pl=(TextView) view1.findViewById(R.id.pl);
holder.min=(TextView) view1.findViewById(R.id.min);
final Items model = itemsArrayList.get(position);
holder.sr.setText(String.valueOf(itemsArrayList.get(position).getSrno()));
holder.item.setText(String.valueOf(itemsArrayList.get(position).getItemname()));
holder.rate.setText(String .valueOf(itemsArrayList.get(position).getFixedrate()));
holder.qty.setText(String.valueOf(itemsArrayList.get(position).getQuantity()));
holder.price.setText(String .valueOf(itemsArrayList.get(position).getRate()));
holder.pl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity(model.getQuantity() + 1);
model.setRate(model.getQuantity()*model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
});
holder.min.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(model.getQuantity()>0) {
model.setQuantity(model.getQuantity() - 1);
model.setRate(model.getQuantity() * model.getFixedrate());
holder.qty.setText(String.valueOf(model.getQuantity()));
holder.price.setText(String.valueOf(model.getRate()));
notifyDataSetChanged();
}
}
});
return view1;
}
}
Items.java
public class Items implements Serializable {
int srno,fixedrate,quantity,rate;
String itemname;
public Items(int srno, String itemname, int fixedrate, int quantity, int rate) {
this.srno = srno;
this.itemname = itemname;
this.fixedrate = fixedrate;
this.quantity = quantity;
this.rate = rate;
}
public int getSrno() {
return srno;
}
public void setSrno(int srno) {
this.srno = srno;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public int getFixedrate() {
return fixedrate;
}
public void setFixedrate(int fixedrate) {
this.fixedrate = fixedrate;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
}
Custom_Trial.java
public class Custom_Trial extends BaseAdapter {
Activity a;
private ArrayList<Items> data = new ArrayList<>();
public Custom_Trial(Activity a, ArrayList<Items> data) {
this.a = a;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView sr, it, qty, amt;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
LayoutInflater li = a.getLayoutInflater();
View view = li.inflate(R.layout.customtrial, parent, false);
holder.sr = (TextView) view.findViewById(R.id.head1);
holder.it = (TextView) view.findViewById(R.id.head2);
holder.qty = (TextView) view.findViewById(R.id.head3);
holder.amt = (TextView) view.findViewById(R.id.head4);
Items m = data.get(position);
holder.sr.setText(String.valueOf(m.getSrno()));
holder.it.setText(m.getItemname());
holder.qty.setText(String.valueOf(m.getQuantity()));
holder.amt.setText(String.valueOf(m.getRate()));
return view;
}
}
Trial.java
public class Trial extends Activity{
ListView listnew;
private ArrayList<Items> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trial);
listnew = (ListView) findViewById(R.id.newlist);
data.addAll((ArrayList<Items>) getIntent().getSerializableExtra("data"));
Custom_Trial ct = new Custom_Trial(this,data);
listnew.setAdapter(ct);
}
}
It's because you passing original list. You're updating values inside adapter and passing not updated list fromadapter, but original. Write method inside adapter to return your updated list.
Inside Custom.java adapter:
public ArrayList<Items> getItems(){
ArrayList<Items> quantityArrayList;
Items item;
for (int i = 0; i < itemsArrayList.size(); i++){
item = itemsArrayList.get(i);
if (item.getQuantity() > 0)
quantityArrayList.add(item);
}
return quantityArrayList;
}
And inside MainActivity onCreate() should look like this. After clicking show button you're going to get Items from Custom Adapter whose quantity >0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_item = (ListView) findViewById(R.id.listdetails);
searchview=(SearchView)findViewById(R.id.searchView);
show = (Button) findViewById(R.id.btnview);
itemsArrayList=new ArrayList<>();
itemsArrayList.add(new Items(1,"Book",20,0,0));
itemsArrayList.add(new Items(2,"Pen",25,0,0));
itemsArrayList.add(new Items(3,"Scale",10,0,0));
itemsArrayList.add(new Items(4,"Eraser",5,0,0));
Custom c = new Custom(this,itemsArrayList);
list_item.setAdapter(c);
list_item.setTextFilterEnabled(true);
setupSearchView();
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Trial.class);
List<Items> quantityList = c.getItems();
intent.putExtra("data", quantityList);
startActivity(intent);
}
});
}

RecyclerView notifyDatasetChanged not working

I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.

Refresh fragment from adapter

I have ListView with items in my fragment. Every item has counter for example
Item 1 - 4
Item 2 - 5
On the top of the fragment I have textView with sum of all elements : sum - 9. I can delete Item with click on image on the item row. In adapter (getView()) it goes like this :
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mParts.remove(part);
notifyDataSetChanged();
dialog.dismiss();
}
});
The item is being removed from list but counter doesn't change value - for example Item 2 was removed but counter still shows 5. I update it in onResume() method and it works but only if I leave fragment and come back to it. I try to write update method in fragment and use it in adapter - I created constructor with fragment :
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,InvFragment mFragment) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mFragment = mFragment;
}
but when I call fragment.something I get null point exception :/ How can I refresh fragment/counter textView from adapter ? I also tried to set fragment again but it doesn't work.
Part of my adapter (it's quite long)
public class PartAdapter extends ArrayAdapter {
private OnUpdateListener listener;
public interface OnUpdateListener {
void onUpdate(String text);
}
public void setOnUpdateListner(OnUpdateListener listener) {
this.listener = listener;
}
private List<Part>mParts;
private LayoutInflater mInflater;
private TextView mPartName;
public CheckBox mState;
private ImageView mActionArrow;
public static final String TAG = PartAdapter.class.getSimpleName();
private static final int CAM_REQUEST = 1313;
private InvActivity mActivity;
private AdapterCallback mAdapterCallback;
private TextView mCounter;
private ImageView mDelete;
private InvFragment mFragment;
public boolean shouldScan = true;
private final byte[] pal = new byte[]{
(byte) 0xDA, (byte) 0xAD, // const
(byte) 0x04, (byte) 0x74, (byte) 0x31, // com
(byte) 0xe7, (byte) 0x64 //last
};
private final byte[] readId = new byte[]{
(byte) 0xDA, (byte) 0xAD, // const
(byte) 0x04, (byte) 0x6f, (byte) 0x69, // com
(byte) 0xec, (byte) 0x6e //last
};
private UsbManager usbManager;
private UsbDevice device;
public List<String> codes;
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,AdapterCallback callback) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mAdapterCallback = callback;
}
public PartAdapter(Context context, int resource, List objects, InvActivity mActivity,InvFragment mFragment) {
super(context, resource,objects);
this.mParts = objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mActivity=mActivity;
this.mFragment = mFragment;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView=mInflater.inflate(R.layout.part_item,parent,false);
mState = (CheckBox) convertView.findViewById(R.id.state_chb);
mDelete = (ImageView)convertView.findViewById(R.id.delete_car);
mDelete.setVisibility(View.INVISIBLE);
final Part party = mParts.get(position);
if(party.isScan() || party.getType().contentEquals("2")) {
mState.setChecked(true);
} else if (!party.isScan()){
mState.setChecked(false);
}
if(party.getType().contentEquals("2"))
mDelete.setVisibility(View.VISIBLE);
if(mParts.get(position).getClass().isInstance(new Part())) {
final Part part = (Part) mParts.get(position);
mPartName = (TextView)convertView.findViewById(R.id.car_name_tv);
mState = (CheckBox) convertView.findViewById(R.id.state_chb);
mPartName.setText(part.getName());
mActionArrow = (ImageView)convertView.findViewById(R.id.arrow_action);
mCounter = (TextView)convertView.findViewById(R.id.car_count_tv);
mCounter.setText(part.getQuantity());
if(!part.isScan()) {
mState.setChecked(false);
} else if(part.isScan() || part.getType().contentEquals("2")) {
mState.setChecked(true);
}
mActionArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_context_menu);
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int totalSum = 5;
int partValue = 2;
mParts.remove(part);
notifyDataSetChanged();
dialog.dismiss();
if(listener != null){
listener((totalSum - partValue).toString());
}
}
});
LinearLayout photo = (LinearLayout)dialog.findViewById(R.id.photo_layout);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mActivity.dispatchTakePictureIntent();
}
});
LinearLayout note = (LinearLayout)dialog.findViewById(R.id.note_layout);
note.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
final Dialog noteDialog = new Dialog(getContext());
noteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteDialog.setContentView(R.layout.dialog_note);
final EditText noteET = (EditText)noteDialog.findViewById(R.id.note_et);
if(!part.getNote().contentEquals("null"))
noteET.setText(part.getNote());
Button save = (Button)noteDialog.findViewById(R.id.save_button);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
part.setNote(noteET.getText().toString());
noteDialog.dismiss();
}
});
noteDialog.show();
Button cancel = (Button) noteDialog.findViewById(R.id.cancel_button);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
}
});
}
});
LinearLayout values = (LinearLayout)dialog.findViewById(R.id.values_layout);
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog noteDialog = new Dialog(getContext());
noteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteDialog.setContentView(R.layout.dialog_note);
final EditText noteET = (EditText)noteDialog.findViewById(R.id.note_et);
noteET.setInputType(InputType.TYPE_CLASS_NUMBER);
Button save = (Button)noteDialog.findViewById(R.id.save_button);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
part.setQuantity(noteET.getText().toString());
noteDialog.dismiss();
dialog.dismiss();
}
});
noteDialog.show();
Button cancel = (Button) noteDialog.findViewById(R.id.cancel_button);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
dialog.dismiss();
}
});
}
});
dialog.show();
}
});
}
return convertView;
}
and from my activity :
public void onUpdate(String value){
mCountTV.setText(value);
}
private void createAdapter() {
adapter.setOnUpdateListner(this);
}
}
You can follow a process like below.
In your PartAdapter set a listener which will implemented in Fragment used to update value of sum text view.
class PartAdapter {
private OnUpdateLitener listener;
public interface OnUpdateListener {
void onUpdate(String text);
}
public void setOnUpdateListner(OnUpdateListener listener) {
this.listener = listener;
}
// in your getView() method
final LinearLayout delete = (LinearLayout)dialog.findViewById(R.id.delete_layout);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mParts.remove(part);
notifyDataSetChanged();
if(listener != null){
listener.onUpdate(String.valueOf(totalSum - partValue));
}
dialog.dismiss();
}
});
}
In your fragment
class MyFragment {
private OnUpdateListener listener;
void onAttach(Activity activity){
if(!(activity instaceof PartAdapter.OnUpdateListener)){
throw new IllegalStateException("Must implement OnUpdateListener");
}
listener = (PartAdapter.OnUpdateListener) activity;
}
private void createAdapter() {
PartAdapter adapter = new PartAdapter(getContext(), R.layout.part_item, mParts, mActivity, new AdapterCallback() {
#Override
public void onMethodCallback() {
Log.e(TAG, "onMethodCallback: ");
}
});
adapter.setOnUpdateListener(this);
mPartsLV.setAdapter(adapter);
}
}
In your activity
class MainActivity implements PartAdapter.OnUpdateListener {
public void onUpdate(String value){
textView.setText(value);
}
}

Categories

Resources