I have main activity which contains fragments. One of the fragment is calling dialogFragment for new item entry. This new item is specified by Serializable class.
Just to be more specific:
item.java
public class Item implements Serializable {
private String mTitle;
private String mDescription;
private Boolean mTrue;
//getters and setters
public String getTitle() {
return mTitle;
}
public void setTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String mDescription) {
this.mDescription = mDescription;
}
public Boolean isTrue() {
return mTrue;
}
public void setTrue(Boolean mTrue) {
this.mTrue = mTrue;
}
}
DialogNewItem
public class DialogNewItem extends DialogFragment {
//filters state holder
Boolean isTrue = false;
//filters state end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.new_item, null);
final EditText editTitle = (EditText) dialogView.findViewById(R.id.editTitle);
final EditText editDescription = (EditText) dialogView.findViewById(R.id.editDescription)
//filter icons
final ImageView ivIsTrue = (ImageView) dialogView.findViewById(R.id.filterTrue);
//filter icons end
//onClickListener for filter icons
ivIsTrue.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (isTrue == false) {
ivIsTrue.setBackgroundResource(R.drawable.border_white);
ivIsTrue.setImageResource(R.drawable.true_white);
isTrue = true;
} else {
ivIsTrue.setBackgroundResource(R.drawable.border_green);
ivIsTrue.setImageResource(R.drawable.true_green);
isTrue = false;
}
}
});
Button btnCancel = (Button) dialogView.findViewById(R.id.btnCancel);
Button btnOK = (Button) dialogView.findViewById(R.id.btnOK);
builder.setView(dialogView);
//cancel button
btnCancel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
dismiss();
}
});
//give button
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
dismiss();
}
});
return builder.create();
}
}
Now, I want to pass newItem from DialogNewItem (btnOK) to a listView Fragment. In other words I want to make a listView Fragment which will contain all the new items created in DialogNewItem.
I was trying different methods (set/getFragment, ArrayList, different interfaces, etc) but some how non of it works. I have no problem with passing newItem to listView in an activity:
//get the reference to dashboard
Dashboard callingActivity = (Dashboard) getActivity();
//pass new item back to dashboard
callingActivity.createNewItem(newItem);
and then dashboard activity:
public class Dashboard extends AppCompatActivity {
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
mItemAdapter = new ItemAdapter();
ListView listItem = (ListView) findViewById(R.id.listView);
listItem.setAdapter(mItemAdapter);
}
//handle clicks on listView
listItem.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick (AdapterView<?> adapter, View view, int whichItem, long id ){
//creating temporary item which is reference to the clicked item
Item tempItem = mItemAdapter.getItem(whichItem);
//new dialog window
DialogShowItem dialog = new DialogShowItem();
//send reference to the item to be shown
dialog.sendItemSelected(tempItem);
//show the dialog window with the item
dialog.show(getFragmentManager(),"");
}
});
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup){
//has been inflated already
if (view==null){
//creating layout inflater
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//instantiate view by inflating inflater (listItem layout)
view = inflater.inflate(R.layout.listitem, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
//grabbing the refrence to all variables
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide not relevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
//category with different image src
return view;
}
and everything works perfectly, but when I want to do the same with Fragment instead of Activity, somehow I cannot make it work.
I would appreciate any help. Thanx
Fragment (with listview):
public class ListItems extends ListFragment {
private ItemAdapter mItemAdapter;
public void createNewItem(Item i) {
mItemAdapter.addItem(i);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstatceState) {
View view = inflater.inflate(R.layout.list_items, container, false);
//Item adapter
mItemAdapter = new ItemAdapter();
final ListView listItems = (ListView) view.findViewById(R.id.listView);
listItems.setAdapter(mItemAdapter);
//floating give button
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogNewItem dialog = new DialogNewItem();
dialog.show(getFragmentManager(), "");
}
});
//handle clicks on itemList
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int whichItem, long id) {
Item tempItem = mItemAdapter.getItem(whichItem);
DialogShowItem dialog = new DialogShowItem();
dialog.sendItemSelected(tempItem);
dialog.show(getFragmentManager(), "");
}
});
return view;
}
#Override
protected void onPause() {
super.onPause();
mItemAdapter.saveItems();
}
public class ItemAdapter extends BaseAdapter {
List<Item> itemList = new ArrayList<Item>();
private JSONSerializer mSerializer;
public ItemAdapter() {
mSerializer = new JSONSerializer("myProject.json", getActivity().getApplicationContext());
try {
itemList = mSerializer.load();
} catch (Exception e) {
itemList = new ArrayList<Item>();
Log.e("Error loading items: ", "", e);
}
}
public void saveItems() {
try {
mSerializer.save(itemList);
} catch (Exception e) {
Log.e("Error saving items: ", "", e);
}
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Item getItem(int whichItem) {
return itemList.get(whichItem);
}
#Override
public long getItemId(int whichItem) {
return whichItem;
}
public void addItem(Item n) {
itemList.add(n);
notifyDataSetChanged();
}
#Override
public View getView(int whichItem, View view, ViewGroup viewGroup) {
if (view==null) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_items, viewGroup, false);
}
Item tempItem = itemList.get(whichItem);
TextView txtTitle = (TextView) view.findViewById(R.id.txtTitle);
TextView txtDescription = (TextView) view.findViewById(R.id.txtDescription);
ImageView ivTrue = (ImageView) view.findViewById(R.id.imgSmTrue);
//setting text variables
txtTitle.setText(tempItem.getTitle());
txtDescription.setText(tempItem.getDescription());
//hide irrelevant images
if (!tempItem.isTrue()){
ivTrue.setVisibility(View.INVISIBLE);
} else {ivTrue.setVisibility(View.VISIBLE);}
return view;
}
}
}
It's a drawer activity so I'm showing it after drawer item click:
private void switchFragment(int position) {
Fragment fragment = null;
String fragmentID = "";
switch (position) {
case 0:
fragmentID = "LISTITEMS";
fragment = new ListItems();
break;
case 1:
fragmentID = "PROFILE";
fragment = new Profile();
break;
default:
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentHolder, fragment, fragmentID).commit();
//close the drawer
mDrawerLayout.closeDrawer(mNavDrawerList);
}
You can make a public method in ListItems fragment class in which you receive an Item class object and add it in adapter. And then inside your DialogNewItem Fragment, On OK Button click, you can search the ListItems using SupportFragmentManager by using its tag and call the public method you wrote.
The following code might help you.
DialogNewItem class
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//new item
final Item newItem = new Item();
//Set its variables to match the users entries on the form
newItem.setTitle(editTitle.getText().toString());
newItem.setDescription(editDescription.getText().toString());
newItem.setTrue(isTrue);
FragmentManager manager = getActivity().getSupportFragmentManager();
ListItems fragment = (ListItems)manager.findFragmentByTag("LISTITEMS");
if(fragment != null){
fragment.createNewItem(newItem);
}
dismiss();
}
});
In your ListItems fragment the following code will depict an ItemAdapter as the data member of the ListViewFragment class and below that is the method you can call to add the item in the adapter.
private ItemAdapter mItemAdapter;
public void createNewItem(Item n) {
mItemAdapter.addItem(n);
}
Related
So I have an activity with a listview inside of it and when I click a delete button I want to remove the object from the list. I already know how to find which object I want to remove and remove it from the list that populates my array adapter but I am not sure what i need to do to call the .notifyDataSetChanged() routine which Is what I believe I need to do. Any help would be much appreciated.
My activity code
public class MealActivity2 extends AppCompatActivity {
private ListView lv;
public static ArrayList<Model> modelArrayList;
private CustomAdapter customAdapter;
private Button btnnext;
private String[] fruitlist = new String[]{"Apples", "Oranges", "Potatoes", "Tomatoes","Grapes"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
Integer numFoodItems = ((Globals) getApplication()).getLength();
lv = (ListView) findViewById(R.id.lv);
btnnext = (Button) findViewById(R.id.next);
modelArrayList = getModel(numFoodItems);
customAdapter = new CustomAdapter(this);
lv.setAdapter(customAdapter);
btnnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MealActivity2.this,NextActivity.class);
startActivity(intent);
}
});
}
// this builds the array list of model opbjects that will be used by the adapter to populate
// the list view dynamically
private ArrayList<Model> getModel(Integer length){
ArrayList<Model> list = new ArrayList<>();
for(int i = 0; i < length; i++){
FoodDetailsPost food = ((Globals) getApplication()).getFoodList().get(i);
Model model = new Model();
model.setNumber(((Globals) getApplication()).getServing(i));
model.setFruit(food.getDescription());
list.add(model);
}
return list;
}
}
and here is my custom adapter code if you look near the end at the last comment that is where i need to notify my activity that I have changed the contents of the list and should update the displaying items
public class CustomAdapter extends BaseAdapter {
private Context context;
private adapterGlobalAccess g = new adapterGlobalAccess();
private CustomAdapter customAdapter;
public CustomAdapter(Context context) {
this.context = context;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return MealActivity2.modelArrayList.size();
}
#Override
public Object getItem(int position) {
return MealActivity2.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.tvFruit = (TextView) convertView.findViewById(R.id.animal);
holder.tvnumber = (TextView) convertView.findViewById(R.id.number);
holder.btn_edit = (Button) convertView.findViewById(R.id.plus);
holder.btn_minus = (Button) convertView.findViewById(R.id.minus);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.tvFruit.setText(MealActivity2.modelArrayList.get(position).getFruit());
holder.tvnumber.setText(String.valueOf(MealActivity2.modelArrayList.get(position).getNumber()));
holder.btn_edit.setTag(R.integer.btn_plus_view, convertView);
holder.btn_edit.setTag(R.integer.btn_plus_pos, position);
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_edit.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_edit.getTag(R.integer.btn_plus_pos);
Double number = Double.parseDouble(tv.getText().toString()) + 1;
tv.setText(String.valueOf(number));
MealActivity2.modelArrayList.get(pos).setNumber(number);
g.setServing(pos, number);
}
});
holder.btn_minus.setTag(R.integer.btn_minus_view, convertView);
holder.btn_minus.setTag(R.integer.btn_minus_pos, position);
holder.btn_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) holder.btn_minus.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.number);
Integer pos = (Integer) holder.btn_minus.getTag(R.integer.btn_minus_pos);
((Globals) context.getApplicationContext()).remove(pos);
MealActivity2.modelArrayList.remove(pos);
// i need to do .notifyDataSetChanged() here but im not sure how
}
});
return convertView;
}
You can just use a interface to solve the problem
CustomAdapter
public class CustomAdapter extends BaseAdapter {
...
private CustomAdapterListener listener;
interface CustomAdapterListener{
void itemClick();
}
public CustomAdapter(Context context, CustomAdapterListener listener) {
this.context = context;
this.listener = listener;
}
MainActivity2
public class MealActivity2 extends AppCompatActivity implements CustomAdapterListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal2);
...
customAdapter = new CustomAdapter(this, this);
}
#Override
public void itemClick() {
// you can do .notifyDataSetChanged() here
}
after that you can use listener to callback to Activity and do anything you want
CustomAdapter
#Override
public void onClick(View v) {
listener.itemClick();
// i need to do .notifyDataSetChanged() here but im not sure how
}
A silly question but I am new to Android and I’ve spent a few hours looking around but can’t find the answer.
I have a dialog fragment with a recyclerview in it. I want the dialog to close when the user clicks a recyclerview item. How do I call dismiss() from the listener in recyclerview adapter?
I've tried a listener for the recyclerview in the dialog fragment but it does nothing. please help.
This is the dialog fragment. At the bottom onClick dismisses it:
public class EvMySchedDlg extends DialogFragment implements View.OnClickListener {
View view;
String eventId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.event_my_sched, container, false);
ImageView closeButton = view.findViewById(R.id.closeButton3);
closeButton.setOnClickListener(this);
final TextView eventNameBox = view.findViewById(R.id.eventNameBox);
eventNameBox.setOnClickListener(this);
TextView coNameBox = view.findViewById(R.id.coNameBox);
Bundle extraData = getArguments();
eventId = extraData.getString("eventId");
String coName = extraData.getString("coName");
String eventName = extraData.getString("eventName");
coNameBox.setText(coName);
eventNameBox.setText(eventName);
//get list of days from server
String userId = ((DrawerActivity)getContext()).getUserData("userId");
final String[] cred = new String[]{"user_id", userId, "event_id", eventId};
VolleyCalls.postRequest(this.getContext(), "getEventDays", cred, new VolleyCalls.ServerReply() {
#Override
public void onSuccess(String theReply){
final List<EvMySchedData> dayList = new ArrayList<>();
EvMySchedAdapter tAdapter = new EvMySchedAdapter(dayList);
RecyclerView recyclerView = view.findViewById(R.id.schedRecycler);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(recyclerView.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(tAdapter);
tAdapter.emptyRecycler();
try {
JSONObject jsonServerReply = new JSONObject(theReply);
int evCount = jsonServerReply.getInt("recCount");
EvMySchedData thisLine;
if (evCount > 0) {
JSONObject cRec =null;
for (int thisRec=0; thisRec<evCount; thisRec++ ) {
cRec = jsonServerReply.getJSONObject(String.valueOf(thisRec));
thisLine = new EvMySchedData(cRec.getString("day_date"), cRec.getString("day_times"), cRec.getString("role"), cRec.getString("room"), view.getContext());
dayList.add(thisLine);
}
}
} catch (Exception e) {
}
}
public void onError(String error) {
}
});
return view;
} // end onCreateView
public void onClick(View v) {
this.dismiss();
}
}
The recyclerview has the picture of an eye on each line. I want to load a new fragment and close the dialog fragment when the eye is clickd. This is the adapter code:
public class EvMySchedAdapter extends RecyclerView.Adapter<EvMySchedAdapter.EventViewHolder> {
private List<EvMySchedData> dayList;
public EvMySchedAdapter(List<EvMySchedData> dayList) {
this.dayList = dayList;
}
#Override
public EvMySchedAdapter.EventViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_my_sched_row, parent, false);
ImageView eye = itemView.findViewById(R.id.dayOverviewButton);
try {
eye.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Load a new fragment
//dismiss the dialog
}
});
} catch (Exception e) {
}
return new EvMySchedAdapter.EventViewHolder(itemView);
}
#Override
public void onBindViewHolder(EvMySchedAdapter.EventViewHolder holder, int position) {
holder.dayDateBox.setText(dayList.get(position).getDayDate());
holder.dayTimeBox.setText(dayList.get(position).getDayTime());
holder.dayRoleBox.setText(dayList.get(position).getDayRole());
holder.dayRoomBox.setText(dayList.get(position).getDayRoom());
} // end onBindViewHolder
#Override
public int getItemCount() {
return dayList.size();
}
public class EventViewHolder extends RecyclerView.ViewHolder {
public TextView dayDateBox;
public TextView dayTimeBox;
public TextView dayRoleBox;
public TextView dayRoomBox;
public Context context;
public EventViewHolder(View view) {
super(view);
dayDateBox = view.findViewById(R.id.dateBox);
dayTimeBox = view.findViewById(R.id.timeBox);
dayRoleBox = view.findViewById(R.id.roleBox);
dayRoomBox = view.findViewById(R.id.roomBox);
}
}
public void emptyRecycler() {
final int size = dayList.size();
dayList.clear();
notifyItemRangeRemoved(0, size);
}
}
Thanks
Add to the adapter a constructor that receive DialogFragment and save it as a field.
When you create the Adapter do new EvMySchedAdapter(dayList, EvMySchedDlg.this);
Inside the onClick call dialgFragment.dismiss();
for Kotlin Users
class SomeAdapter(private val dialog: BottomSheetDialog):RecyclerView.Adapter<SomeAdapter.ViewHolder>()
holder.itemView.setOnClickListener{
dialog.dismiss()
}
In MainActivity I have NavigationDrawer. For each menu item, I have a fragment class with a corresponding layout. One of them is MyCardFragment.java. In this fragment, I am showing CardView through RecyclerView.
My CardView contains some TextViews and an ImageView. What I wanted is when a user clicks a widget it will open a custom input dialog (contains a TextView, an EditText, a positive button, and a negative button) for updating data in Firebase Real-time database. I created a dialog fragment class, but don't know how to implement it in my adapter class.
This is my main activity which holds RecyclerView and CardView:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth=FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser != null){
myRef = FirebaseDatabase.getInstance().getReference().child("user").child(currentUser.getUid());
}
mContext = MainActivity.this;
mDrawerLayout = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_action_name);
NavigationView navigationView = findViewById(R.id.nav_view);
//navigationView.inflateHeaderView(R.layout.nav_header);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
switch (menuItem.getItemId()) {
case R.id.nav_myCards:
menuItem.setChecked(true);
getSupportActionBar().setTitle("MY Cards");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,new MyCardFragment())
.commit();
break;
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Respond when the drawer's position changes
}
#Override
public void onDrawerOpened(View drawerView) {
// Respond when the drawer is opened
}
#Override
public void onDrawerClosed(View drawerView) {
// Respond when the drawer is closed
}
#Override
public void onDrawerStateChanged(int newState) {
// Respond when the drawer motion state changes
}
}
);
navigationView.getMenu().getItem(0).setChecked(true);
//Highlighted
//onNavigationItemSelected(navigationView.getMenu().getItem(0));
setupFirebaseAuth();
if (currentUser != null){
//updateNavHeader();
}
}
Custom Dialog Fragment:
DialogCompanyAddress.java:
public class DialogCompanyAddress extends DialogFragment {
public DialogCompanyAddress() {
// Required empty public constructor
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.fragment_dialog_company_address,null));
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//save data to the firebase
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Do
}
});
return builder.create();
}
}
finally the adapter:
RecyclerviewAdapter.java:
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
Context mContext;
List<Template> listdata;
public RecyclerviewAdapter(Context context,List<Template> listdata) {
this.mContext = context;
this.listdata = listdata;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
/*// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;*/
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview,parent,false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0) {
arr = 0;
} else {
arr=listdata.size();
}
} catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname,tempID;
ImageView logo_image;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(final View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(mContext,"Clicked on Address",Toast.LENGTH_SHORT).show();
DialogCompanyAddress address = new DialogCompanyAddress();
//address.show(getSupportFragmentManager);--->This line give me error
}
});
}
}
use a interface in your adapter like below
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder> {
public interface ClickListner {
void IconClick(Template template);
}
Context mContext;
List<Template> listdata;
private final ClickListner listner;
public RecyclerviewAdapter(Context context, List<Template> listdata, ClickListner listner) {
this.mContext = context;
this.listdata = listdata;
this.listner = listner;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.cardview, parent, false);
return new MyHolder(view);
}
public void onBindViewHolder(MyHolder holder, int position) {
holder.pname.setText(listdata.get(position).getP_name());
holder.pdesignation.setText(listdata.get(position).getP_designation());
holder.pemail.setText(listdata.get(position).getP_email());
holder.pphone.setText(listdata.get(position).getP_phone());
holder.cname.setText(listdata.get(position).getC_name());
holder.caddress.setText(listdata.get(position).getC_address());
//holder.tempID.setText(listdata.get(position).getTempID());
Glide.with(mContext).load(listdata.get(position).getC_logo()).into(holder.logo_image);
holder.bind(listdata.get(position), listner);
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try {
if (listdata.size() == 0) {
arr = 0;
} else {
arr = listdata.size();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder {
TextView pname, caddress, pemail, pdesignation, pphone, cname, tempID;
ImageView logo_image;
public MyHolder(final View itemView) {
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
logo_image = itemView.findViewById(R.id.imageView);
tempID = itemView.findViewById(R.id.tempID);
// caddress.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// //Toast.makeText(mContext,"Clicked on
Address",Toast.LENGTH_SHORT).show();
// DialogCompanyAddress address = new DialogCompanyAddress();
// //address.show(getSupportFragmentManager);--->This line give me
error
//
// }
// });
}
public void bind(final Template template, final ClickListner Listner) {
// DeleteIcon.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// delListner.onDeleteIconClick(card, position);
// }
// });
caddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listner.IconClick(template);
}
});
}
}
and in your fragment you need to initialize the adapter. when initialize you can override the ClickListner interface.
I have created a listview but when i delete a element, it doesn't refresh. I have tried
adapter.notifyDataSetChanged();
and
getListView().invalidateViews();
in mainactivity:
case R.id.ordini:
Ordini O = new Ordini();
android.app.FragmentManager fragmentManager0 = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction0 = fragmentManager0
.beginTransaction();
fragmentTransaction0.replace(R.id.frame, O);
fragmentTransaction0.commit();
Ordini.java
public class Ordini extends ListFragment implements AdapterView.OnItemClickListener {
int ArraySize;
CustomAdapterOrdini adapter;
private List<RowItemOrdini> rowItems;
Button SendButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.ordini, null, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArraySize = MainActivity.ArrayProdotto.size();
SendButton = (Button) getActivity().findViewById(R.id.send_btn);
rowItems = new ArrayList<RowItemOrdini>();
for (int i = 0; i < ArraySize; i++) {
RowItemOrdini items = new RowItemOrdini(
MainActivity.ArrayProdotto.get(i),
R.drawable.ic_delete_black_24dp,
MainActivity.ArrayCode.get(i),
MainActivity.ArrayPrezzo.get(i),
MainActivity.ArrayColli.get(i),
MainActivity.ArrayQuantita.get(i));
rowItems.add(items);
}
adapter = new CustomAdapterOrdini(getActivity(), rowItems);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
SendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "invio ordine in corso... ", Toast.LENGTH_SHORT)
.show();
SendOrdine();
}
});
}
#Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
getListView().invalidateViews();
}
CustomAdapterOrdini
public class CustomAdapterOrdini extends BaseAdapter {
Context context;
List<RowItemOrdini> rowItem;
ImageView Del;
TextView Colli, Prezzo, Quantita, Code, Product;
CustomAdapterOrdini(Context context, List<RowItemOrdini> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_ordini, null);
}
Code = (TextView) convertView.findViewById(R.id.prodcode);
Product = (TextView) convertView.findViewById(R.id.PRODOTTO);
Del = (ImageView) convertView.findViewById(R.id.del);
Colli = (TextView) convertView.findViewById(R.id.T1);
Prezzo = (TextView) convertView.findViewById(R.id.T2);
Quantita = (TextView) convertView.findViewById(R.id.T3);
Del.setFocusable(true);
Del.setClickable(true);
Del.setTag(convertView);
final RowItemOrdini row_pos = rowItem.get(position);
// setting the image resource and title
Del.setImageResource(R.drawable.ic_delete_black_24dp);
Product.setText(row_pos.getTitle());
Code.setText(row_pos.getCode());
Colli.setText(row_pos.getColli());
Prezzo.setText(row_pos.getPrezzo());
Quantita.setText(row_pos.getQuantita());
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayQuantita.remove(0);
MainActivity.ArrayCode.remove(0);
MainActivity.ArrayProdotto.remove(0);
MainActivity.ArrayColli.remove(0);
MainActivity.ArrayPrezzo.remove(0);
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
}
});
return convertView;
}
Can someone help me with listview refresh?
I want refresh my listview in CustomAdapterOrdini or in onResume in Ordini.java.
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
There is a simple way?
Thank you so much!
You have declare ArrayProdotto in your MainActivity and you are display your data from rowItem in CustomAdapterOrdini. You have to remove your data from both list and call notifyDataSetChanged();
Like as below code.
Del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE I WANT REFRESH MY LISTVIEW
MainActivity.ArrayProdotto.remove(position); //Delete from main source
rowItem.remove(position) // Delete from adapter
CustomAdapter.ShowDialog("Elemento eliminato con successo!", context);
notifyDataSetChanged(); // Refresh Adapter
}
});
1). Remove your item from adapter:
adapter.remove(adapter.getItem(position));
2). Call adapter.notifyDataSetChanged();
You should call notifyDataSetChanged() every time when you deleting item from adapter. Not only in onResume.
Note, that you should remove item from adapter, to change ListView items, not from storage(ArrayList, SQLite, or else).
In my application I'm trying to make navigation between pages by Dropdown navigation menu, but when i'm running the application there is no items in my list
Main Activity
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
//----------------------------------New Variables
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
//----------------------------------
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>(act.getThemedContext(),
android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText( "http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf
/Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
downloadservice.addandstart(value);
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
return false;
}
Custom adapter and SherlockFragmentList
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
//private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
// this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.downloads.get(position).getName());
progressbar.setBottom(downloadservice.downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
Anyone can tell me how to implement my list right and where is my mistake ?
thx a lot
Don't set the layout from your fragment big no no!
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActivity().setContentView(R.layout.downloadlist); // Never do this!
// Also this will do nothing remove this! This should be in your `onActivityCreated()`
// setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Don't override onCreateView in your Fragment, SherlockListFragment creates the ListView layout for you.
If you want to set the adapter, remove your onCreateView and set you adapter in onActivityCreated()
#Override
public void onActivityCreated(Bundle saveState){
setListAdapter(new MyAdapter(getSherlockActivity(), downloadservice.downloads));
}
Setting your setListAdapter(listadapter ); in your Adapter getView is wrong too. If you update your List<?> of data make sure you call notifyDataSetChanged() from the mainThread after you update the list.
Otherwise make sure you layout has a ListView with android:id="#android:id/list" defined otherwise SherlockListView won't have a view to set the adapter too.