I've made a listview and when i click an item, it filters and it shows items that filtered by what i clicked. We can think it is like a treeview.
My question is when i come last item "how can i go back one step in this listview ?". When i click device's back button it returns main activity but i want only returning back in this listview.
OsbItemsListActivity.java
public class OsbItemsListActivity extends AppCompatActivity {
private ListView sobItemsListView;
private Activity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_osb_items_list);
mContext = this;
Intent intent = getIntent();
if(null != intent){
sobItemsListView = (ListView)findViewById(R.id.activity_osb_items_list_view);
SobItemsAdapter sobItemsAdapter = new SobItemsAdapter(mContext);
sobItemsListView.setAdapter(sobItemsAdapter);
sobItemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedItem = (String) parent.getAdapter().getItem(position);
Toast.makeText(mContext, "SOB : " + clickedItem, Toast.LENGTH_SHORT).show();
((SobItemsAdapter)parent.getAdapter()).setNextFilter(clickedItem);
((SobItemsAdapter) parent.getAdapter()).notifyDataSetChanged();
}
});
}
else {
Toast.makeText(mContext, "Listelenecek Veri Yok", Toast.LENGTH_SHORT).show();
}
}
}
And my SobItemsAdapter.java
public class SobItemsAdapter extends BaseAdapter {
public enum STEPS{ SOB, STREET, CONNECTIONARTICLE, INSTALLATION }
Activity mActivity;
List<OsbDownloadItem> osbDownloadItemList;
List<String> visualRows = new ArrayList<String>();
HashMap<String, List<OsbDownloadItem>> map;
STEPS filterStep;
public SobItemsAdapter(Activity activity){
mActivity = activity;
filterStep = STEPS.SOB;
osbDownloadItemList = SharedData.osbDownloadItemList;
setNextFilter("");
}
private void modifyVisualRows(HashMap<String, List<OsbDownloadItem>> _map){
visualRows.clear();
for(String item : _map.keySet()){
visualRows.add(item);
}
}
#Override
public int getCount() {
return visualRows.size();
}
#Override
public String getItem(int position) {
return visualRows.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = mActivity.getLayoutInflater();
View view = inflater.inflate(R.layout.activity_osb_items_row, parent, false);
if(null != view){
((TextView)view.findViewById(R.id.osb_items_sob)).setText(visualRows.get(position));
}
return view;
}
public void setNextFilter(String value){
switch (filterStep){
case SOB:
map = DataFilter.getSobs(osbDownloadItemList);
filterStep = STEPS.STREET;
break;
case STREET:
map = DataFilter.getStreetsBySob(map.get(value));
filterStep = STEPS.CONNECTIONARTICLE;
break;
case CONNECTIONARTICLE:
map = DataFilter.getConnectionArticlesByStreet(map.get(value));
filterStep = STEPS.INSTALLATION;
break;
case INSTALLATION:
map = DataFilter.getInstalliationsByConnectionArticle(map.get(value));
break;
}
modifyVisualRows(map);
}
}
Put this below code in your activity
#Override
public void onBackPressed()
{
if(checkBackPress)
{
checkBackPress =false;
sobItemsAdapter.setNextFilter(STEPS.SOB);
sobItemsAdapter.notifyDataSetChanged();
}
super.onBackPressed();
}
Create one boolean field public boolean checkBackPress=false; in your activity. Set this checkBackPress as true once item clicked on your item click event(checkBackPress=true) and set checkBackPress as false in backpressed
Related
PagerAdapter Class
I am building an app that has many functionalities. I created a tab layout. There are two fragments. How to return fragment in instantiateItem method. The way I did strong textin the output EmployeeAdd fragment is not showing anything. Earlier I created FragmentPagerAdapter. The code was working fine. But since FragmentPagerAdapter deprecated so I switch to PagerAdapter
public class SectionsPagerAdapter extends PagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
private final Context context;
private LayoutInflater layoutInflater;
public SectionsPagerAdapter(Context context) {
this.context = context;
}
int layouts [] = {R.layout.fragment_employee_add, R.layout.fragment_employee_delete};
#Override
public int getCount() {
return layouts.length;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one=layoutInflater.inflate(R.layout.fragment_employee_add,container,false);
View two=layoutInflater.inflate(R.layout.fragment_employee_delete,container,false);
View viewArray [] = {one, two};
container.addView(viewArray[position]);
switch (position){
case 0:
return new EmployeeAddFragment();
case 1:
return new EmployeeDeleteFragment();
}
//container.addView(one);
return container;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return context.getResources().getString(TAB_TITLES[position]);
}
#Override
public boolean isViewFromObject(#NonNull #NotNull View view, #NonNull #NotNull Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
}
EmployeeAddFragment
this is my fragment. It has many editText and a button that adds all the data to database. I couldn't resolve the problem. Please help me
public class EmployeeAddFragment extends Fragment {
DBHelper myDB;
EditText substationNumber, employeeId, employeeName, password, phoneNumber, dateOfJoining, permanentOrTemporary, designation, security;
Button addEmployee;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View rootView = inflater.inflate(R.layout.fragment_employee_add, container, false);
substationNumber = rootView.findViewById(R.id.substationNumber);
employeeId = rootView.findViewById(R.id.employeeId);
employeeName = rootView.findViewById(R.id.employeeName);
password = rootView.findViewById(R.id.passwordEmployee);
phoneNumber = rootView.findViewById(R.id.phoneNumber);
dateOfJoining = rootView.findViewById(R.id.dateOfJoining);
permanentOrTemporary = rootView.findViewById(R.id.permanentOrTemporary);
designation = rootView.findViewById(R.id.designation);
security = rootView.findViewById(R.id.security);
addEmployee = rootView.findViewById(R.id.addSubstationButton);
if(myDB == null)
myDB = new DBHelper(getActivity());
addEmployee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addEmployeeFunction();
}
});
return rootView;
}
//function to add user to the database by admin
private void addEmployeeFunction() {
//Todo edit this part
Toast.makeText(getActivity().getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_LONG).show();
/*String getEmployeeID = employeeId.getText().toString();
String getEmployeeName = employeeName.getText().toString();
String getPassword = password.getText().toString();
int lengthOfPassword = password.length();
if(TextUtils.isEmpty(getEmployeeID) || TextUtils.isEmpty(getEmployeeName) ||TextUtils.isEmpty(getPassword) )
Toast.makeText(getActivity().getApplicationContext(), "Please enter all the fields.", Toast.LENGTH_LONG).show();
else if(lengthOfPassword < 6)
Toast.makeText(getActivity().getApplicationContext(), "Password length must be greater than 5", Toast.LENGTH_LONG).show();
else{
boolean isInserted = myDB.insertDataIntoDatabase(getEmployeeID, getEmployeeName, getPassword);
if(isInserted)
Toast.makeText(getActivity().getApplicationContext(), "Employee Added Successfully", Toast.LENGTH_LONG).show();
else
Toast.makeText(getActivity().getApplicationContext(), "Entry failed.", Toast.LENGTH_LONG).show();
employeeId.setText("");
employeeName.setText("");
password.setText("");
}*/
}
}
You can go with SmartFragmentStatePagerAdapter
https://guides.codepath.com/android/viewpager-with-fragmentpageradapter
Working on android app' and I want to pass value from my textview that is in a row of a listview and put it in a fragment. I hear about convertView.gettag and settag method put I don't know how to deal with.
My code:
public class EvaluationsFragment extends CustomFragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private Patient mPatient;
private View myView;
private Context context;
private Button btnAjoutEvaluation;
private ListView evaluations_historic_liste;
private List<Evaluation>mEvaluation;
private EvaluationDto mEvaluationDto;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_evaluations, container,false);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
init();
}
private void init(){
evaluations_historic_liste = (ListView)myView.findViewById(R.id.evaluations_historic_liste);
btnAjoutEvaluation = (Button)myView.findViewById(R.id.evaluations_add__btn);
btnAjoutEvaluation.setOnClickListener(this);
TypeEvaluation mNouveauTypeEvaluation;
mPatient =((DossierActivity)mRootActivity).mPatient;
mEvaluationDto = new EvaluationDto(mRootActivity.getApplicationContext());
evaluations_historic_liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EvaluationAdapter.EvaluationItem item = (EvaluationAdapter.EvaluationItem)view.getTag();
openDetailEvaluation(item);
}
});
mEvaluationDto.open();
try{
mEvaluation = mEvaluationDto.getEvaluationsByPatientId(mPatient.getId());
}catch (SQLException e) {
Log.e(Constants.APP_LOG_TAG, e.getMessage());
ACRA.getErrorReporter().handleException(e);
} finally{
mEvaluationDto.close();
}
if(mEvaluation != null && mEvaluation.size() >0){
evaluations_historic_liste.setAdapter(new EvaluationAdapter(mRootActivity,mEvaluation));
}else {
evaluations_historic_liste.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case (R.id.evaluations_add__btn):
openNewEvaluation();
break;
}
}
public void openNewEvaluation(){
Fragment fragment = new EvaluationNouvelleFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new EvaluationNouvelleFragment());
fragmentTransaction.commit();
}
public void openDetailEvaluation(EvaluationAdapter.EvaluationItem item){
EvaluationAdapter evaluationAdapter = new EvaluationAdapter();
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle args = new Bundle();
args.putString(EvaluationDetailHistoriqueFragment.DATA_RECEIVE, /*HERE I NEED TO PUT item_evaluation_nom.setText()*/ );
detail.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, detail).commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class EvaluationAdapter extends BaseAdapter {
private Context mcontext;
private List<EvaluationItem> mItems = new ArrayList<EvaluationItem>();
public EvaluationAdapter(){}
public EvaluationAdapter(Context context, List<Evaluation> values) {
this.mcontext = context;
for (Evaluation e : values) {
mItems.add(new EvaluationItem(e));
}
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public EvaluationItem getItem(int position) {
return mItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
EvaluationItemHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.list_items_historic_evaluations, parent, false);
holder = new EvaluationItemHolder();
holder.item_evaluation_date = (TextView) convertView.findViewById(R.id.item_evaluation_date);
holder.item_evaluation_nom = (TextView) convertView.findViewById(R.id.item_evaluation_nom);
holder.item_evaluation_personnel = (TextView) convertView.findViewById(R.id.item_evaluation_personnel);
holder.item_evaluation_score = (TextView) convertView.findViewById(R.id.item_evaluation_score);
holder.item_evaluation_date_reevaluation = (TextView) convertView.findViewById(R.id.item_evaluation_date_reevaluation);
convertView.setTag(holder);
}else{
holder = (EvaluationItemHolder)convertView.getTag();
}
final EvaluationItem item = getItem(position);
int score = (item.getScoreTV()).intValue();
holder.item_evaluation_date.setText( + " " + item.getDateTV());
holder.item_evaluation_nom.setText(item.getTypeEvalTV());
if (item.getPersonnelTV() != null) {
holder.item_evaluation_personnel.setText( + " " + item.getPersonnelTV());
}
holder.item_evaluation_score.setText( + String.valueOf(score));
if (item.getDateReevalTV() != null) {
holder.item_evaluation_date_reevaluation.setText( item.getDateReevalTV());
}
// convertView.setTag(1,item.getTypeEvalTV());
return convertView;
}
public class EvaluationItem {
private String dateTV;
private String typeEvalTV;
private String personnelTV;
private Double scoreTV;
private String dateReevalTV;
public String getDateTV() {return dateTV;}
public void setDateTV(String dateTV) {
this.dateTV = dateTV;
}
public String getTypeEvalTV() {
return typeEvalTV;
}
public void setTypeEvalTV(String typeEvalTV) {
this.typeEvalTV = typeEvalTV;
}
public String getPersonnelTV() {
return personnelTV;
}
public void setPersonnelTV(String personnelTV) {
this.personnelTV = personnelTV;
}
public Double getScoreTV() {
return scoreTV;
}
public void setScoreTV(Double scoreTV) {
this.scoreTV = scoreTV;
}
public String getDateReevalTV() {
return dateReevalTV;
}
public void setDateReevalTV(String dateReevalTV) {
this.dateReevalTV = dateReevalTV;
}
public EvaluationItem(Evaluation e){
this.dateTV = e.getDate();
this.typeEvalTV = e.getTypeEvaluation().getLibelle();
this.personnelTV = e.getPersonnelLibelle();
this.scoreTV = e.getScore();
this.dateReevalTV = e.getDateReevaluation();
}
}
}
public static class EvaluationItemHolder{
public TextView item_evaluation_date;
public TextView item_evaluation_nom;
public TextView item_evaluation_personnel;
public TextView item_evaluation_score;
public TextView item_evaluation_date_reevaluation;
}
}
You were doing good, you need a Bundle to do this.
First of all create a String where you can keep the value of
holder.item_evaluation_nom.getText();
Then for example you do this :
String itemEvaluation = holder.item_evaluation_nom.getText();
This is the correct Bundle
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle bundle = new Bundle();
bundle.putString("text", itemEvaluation);
detail.setArguments(bundle);
Then to retrieve this you do this :
Bundle bundle = this.getArguments();
if (bundle != null) {
String itemEvaluation = bundle.getString("text", "");
}
hope it helps.
EDIT
You'll need to add an Adapter to your evaluations_historic_liste list.
You can do this doing :
evaluations_historic_liste.setAdapter(new EvaluationAdapter(getActivity(),mEvaluation));
mEvaluation is the List that you have to put data on it.
Then in your ListView add this :
evaluation_historic_liste.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id){
String itemEvaluation = (String) ((TextView)view.findViewById(R.id.item_evaluation_nom)).getText();
//or
String itemEvaluation=(evaluation_historic_liste.getItemAtPosition(position).toString());
}
}
Hello am trying to delete an item from my listview am able to delete item from my db but my adapter is not getting updated I have attached the code below`
public class SavedPolygonFragment extends android.support.v4.app.Fragment implements RefreshListener {
private static String LOG_TAG = SavedPolygonFragment.class.getName();
private String message = "No message";
private ListView shapeList;
private TextView textView;
private Button startMainBtn;
private SavedShapeAdapter savedShapeAdapter;
private long shapeId;
private float scaleFactor;
private List<Shape> savedShapes = new ArrayList<>();
private StartDrawingListener startListener;
private DeleteShapesDialog deleteDialog;
public SavedPolygonFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
startListener = (StartDrawingListener) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
savedShapes = getArguments().getParcelableArrayList("shapes");
AssetLog.verbose(LOG_TAG, "savedshapes.size " + savedShapes.size());
shapeList = (ListView) view.findViewById(R.id.shapeList);
textView = (TextView) view.findViewById(R.id.polygonTitle);
startMainBtn = (Button) view.findViewById(R.id.gotoMain);
startMainBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startListener.startMainReceived();
}
});
if (!savedShapes.isEmpty() && !savedShapes.equals(null) && savedShapes.size() != 0) {
textView.setText("Polygons");
shapeList.setVisibility(View.VISIBLE);
startMainBtn.setVisibility(View.GONE);
if (savedShapeAdapter != null) {
savedShapeAdapter.notifyDataSetChanged();
} else {
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
shapeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MainActivity_.intent(getActivity())
.savedProjectId(ProjectShapesActivity.projId)
.scaleFactor(ProjectShapesActivity.scaleFactor)
.shapeId(((Shape) view.getTag()).getShapeId())
.lineId(-1)
.pointId(-1)
.start();
}
});
}
}
else{
shapeList.setVisibility(View.GONE);
startMainBtn.setVisibility(View.VISIBLE);
textView.setText("Sorry no shapes are saved");
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(shapeList);
}
#Override
public void onRefreshPressed() {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
shapeId = info.id;
menu.add(Menu.NONE, R.id.deleteShapes, Menu.NONE, "Delete");
menu.add(Menu.NONE, R.id.editShapes, Menu.NONE, "Edit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.refresh:
return false;
case R.id.deleteShapes:
if(deleteDialog == null){
Bundle bundle = new Bundle();
bundle.putString("SHAPE", "SHAPE");
bundle.putLong("shapeId", shapeId);
deleteDialog = new DeleteShapesDialog();
deleteDialog.setArguments(bundle);
deleteDialog.show(getActivity().getFragmentManager().beginTransaction(), "showDeleteDialog");
}
return true;
case R.id.editShapes:
return true;
}
return super.onContextItemSelected(item);
}
public void onDataChanged(long shapeid) {
Shape shape;
for (int i = 0; i <savedShapes.size() ; i++) {
shape = savedShapes.get(i);
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
shapeList.removeViewAt(i);
shapeList.invalidate();
savedShapeAdapter.notifyDataSetChanged();
break;
}
}
}
}
`
Now when user selects yes from deleteDialog i wrote a callback to my activity and in the corresponding methods this is what I do
SavedPolygonFragment polygonFragment = new SavedPolygonFragment();
polygonFragment.onDataChanged(shapeId);
Can somebody show me whats wrong
/////EDIT 1
public void onDataChanged(long shapeid) {
savedShapeAdapter.removeItemById(shapeid);
}
and my adapter
public void removeItemById(long itemId){
for(int i =0; i< shapeList.size() ; i++){
if(shapeList.get(i).getShapeId() == itemId){
shapeList.remove(i);
}
}
notifyDataSetChanged();
}
am able to delete item from my db but my adapter is not getting
updated
Problem is caused by :
savedShapes.remove(i);
line.
Currently removing item from ArrayList which is in SavedPolygonFragment class, not from ArrayList which is used by Adapter to fill ListView.
Using current approach try this way will work by setting new Adapter every time:
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
savedShapeAdapter.notifyDataSetChanged();
break;
}
But this is not optimize solution to create and set new object of Adapter every-time when want to update ListView.
Right approach is create a method in SavedShapeAdapter class for removing item for ArrayList which is used by Adapter and then call it inside onDataChanged method:
public void deleteRowItem(int index){
this.savedShapes.remove(index);
this..notifyDataSetChanged();
}
Now call deleteRowItem when want to delete row item from ListView :
if(shape.getShapeId() == shapeid){
savedShapeAdapter.deleteRowItem(i);
break;
}
How can I refresh the view of a fragment, when the back button is pressed?
I have tried this in the onResume method of the fragment but it doesn't work.
OK, here is the code
#SuppressWarnings("unused")
public class RestaurantMenuFragment extends Fragment {
private static final String TAG = "MenuItemsFragment";
private static final String CATEGORIES_KEY = "categories";
private static final String SELECTED_CATEGORY_ID_KEY = "category";
private static final String RESTAURANT_KEY = "restaurant123";
private static final String RESTAURANT_KCITY = "city";
private Spinner mCategoriesSpinner;
private ArrayAdapter<CategoriesResponse.Category> mCategoriesAdapter;
private ListView mListView;
private List<MenuItem> mItems;
private MenuItemsAdapter mItemsAdapter;
private EmptyLayout mEmptyLayout;
private Restaurant mRestaurant;
private int mCategoryId;
private List<CategoriesResponse.Category> mCategories;
private RestaurantActivity mActivity;
private MainApplication mApplication;
private CategoriesResponse mCategoriesResponse;
private ActionBar mActionBar;
private Gson mGson;
int categ;
private ObjectGetter mObjectGetter;
public static RestaurantMenuFragment newInstance(Restaurant restaurant) {
RestaurantMenuFragment fragment = new RestaurantMenuFragment();
Bundle args = new Bundle();
args.putString(RESTAURANT_KEY, new Gson().toJson(restaurant));
String dd=restaurant.city;
Log.i("dd12", dd);
fragment.setArguments(args);
return fragment;
}
public RestaurantMenuFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (RestaurantActivity) getActivity();
mApplication = (MainApplication) mActivity.getApplication();
mActionBar = mActivity.getSupportActionBar();
mGson = new Gson();
mObjectGetter = new ObjectGetter();
mCategories = new ArrayList<CategoriesResponse.Category>();
Log.i("mCategories",""+mCategories);
mItems = new ArrayList<MenuItem>();
Log.i("12345",""+mItems);
mItemsAdapter = new MenuItemsAdapter(getActivity(), mItems);
Bundle args = getArguments();
if (args != null) {
mRestaurant = mGson.fromJson(args.getString(RESTAURANT_KEY),
Restaurant.class);
}
if (savedInstanceState != null) {
mRestaurant = mGson.fromJson(
savedInstanceState.getString(RESTAURANT_KEY),
Restaurant.class);
mCategoryId = savedInstanceState.getInt(SELECTED_CATEGORY_ID_KEY);
mCategoriesResponse = mGson.fromJson(
savedInstanceState.getString(CATEGORIES_KEY),
CategoriesResponse.class);
}
assert mRestaurant != null;
updateCart();
}
public void updateCart() {
View view = mActionBar.getCustomView();
Button cartButton = (Button) view.findViewById(R.id.cartButton);
int nOfItems = 0;
if (mApplication.isCartCreated()) {
nOfItems = mApplication.getCart().getNOfAllItems();
}
cartButton.setText(String.format("%d", nOfItems));
if (nOfItems > 0) {
cartButton.setEnabled(true);
} else {
cartButton.setEnabled(false);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Gson gson = new Gson();
outState.putString(RESTAURANT_KEY, gson.toJson(mRestaurant));
outState.putInt(SELECTED_CATEGORY_ID_KEY, mCategoryId);
outState.putString(CATEGORIES_KEY, gson.toJson(mCategoriesResponse));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.spinner_list, container, false);
RestaurantActivity activity = (RestaurantActivity) getActivity();
String myDataFromActivity = activity.getMyData();
String myDataFromActivity1 = activity.getMyData1();
Log.i("myDataFromActivity",myDataFromActivity);
Log.i("myDataFromActivity1",myDataFromActivity1);
categ=Integer.parseInt(myDataFromActivity1);
mListView = (ListView) view.findViewById(R.id.list122334);
mListView.setAdapter(mItemsAdapter);
Log.d(TAG,"Querying items url "
+ Urls.menuItemsQuery(mRestaurant.id,categ));
mEmptyLayout = EmptyLayout.with(getActivity()).to(mListView)
.setEmptyMessage(R.string.categories_empty_message)
.showLoading();
loadItems();
return view;
}
private void loadItems() {
mEmptyLayout.showLoading();
mItems.clear();
mObjectGetter.getJsonObjectOrDialog(mActivity,
Urls.menuItemsQuery(mRestaurant.id, categ),
ItemsResponse.class,
new ObjectGetter.OnFinishedListener<ItemsResponse>() {
#Override
public void onFinishedLoadingObject(
ItemsResponse itemsResponse) {
mEmptyLayout.showEmpty();
if (itemsResponse != null
&& itemsResponse.items != null) {
mItems.addAll(itemsResponse.items);
}
mItemsAdapter.notifyDataSetChanged();
}
});
}
private class MenuItemsAdapter extends ArrayAdapter<MenuItem> {
private static final String TAG = "MenuItemsAdapter";
public MenuItemsAdapter(Context context, List<MenuItem> menuItems) {
super(context, 0, menuItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MenuItem menuItem = getItem(position);
View view = convertView;
final ViewHolder viewHolder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.menu_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) view.findViewById(R.id.name);
viewHolder.description = (TextView) view.findViewById(R.id.description);
viewHolder.price = (TextView) view.findViewById(R.id.price);
viewHolder.add = (Button) view.findViewById(R.id.add);
viewHolder.selectedView = view.findViewById(R.id.selectedView);
viewHolder.remove = (Button) view.findViewById(R.id.remove);
viewHolder.total = (TextView) view.findViewById(R.id.itemTotal);
viewHolder.quantity = (TextView) view.findViewById(R.id.quantity);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try
{
viewHolder.name.setText(menuItem.name);
viewHolder.description.setText(menuItem.description);
viewHolder.price.setText(String.valueOf(menuItem.price));
}catch(NullPointerException e){
e.printStackTrace();
}
viewHolder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mApplication.createNewCartIfPossibleAndAskIfNot(
getActivity(), mRestaurant,
new MainApplication.OnCreateCartListener() {
#Override
public void onCreateCart(Cart cart) {
cart.addOne(menuItem);
updateItemFromCart(menuItem, viewHolder);
updateCart();
}
});
}
});
viewHolder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mApplication.isCartCreated()) {
return;
}
mApplication.getCart().removeOne(menuItem);
updateItemFromCart(menuItem, viewHolder);
updateCart();
}
});
return view;
}
private void updateItemFromCart(MenuItem menuItem, ViewHolder viewHolder) {
if (!mApplication.isCartCreated()) {
return;
}
int quantity = mApplication.getCart().getNOfItemsOfType(menuItem);
if (quantity > 0) {
viewHolder.selectedView.setVisibility(View.VISIBLE);
} else {
viewHolder.selectedView.setVisibility(View.GONE);
}
viewHolder.quantity.setText(String.valueOf(quantity));
viewHolder.total.setText(String.valueOf(quantity
* menuItem.price));
}
class ViewHolder {
TextView name;
TextView description;
TextView price;
Button add;
View selectedView;
Button remove;
TextView total;
TextView quantity;
}
}
#Override
public void onResume() {
super.onResume();
updateCart();
mItems.clear();
if (mItemsAdapter != null) {
mItemsAdapter.notifyDataSetChanged();
}
}
#Override
public void onDestroy() {
if (mObjectGetter != null) {
mObjectGetter.stopRequests();
}
super.onDestroy();
}
}
Now, i want to update the listvieww data when the user pressed the back button. I set the new loadItems() method in the onResume() Method of the Fragment. This Method is called but the old listview data appears and new data also appears...
Back button should be handled from Activity.
You can override onBackPressed in Activity and call a function on corresponding fragment to reloadItems().
Here are your 3 options I could think of.
Get reference to Fragment and call function to reLoadItems and its better to define an interface for this communication which fragment implements.
Better solution than first one. Add a LocalBroadcast which Activity broadcasts and your fragment listens and updates data on receiving broadcast.
Example for this :
http://luboganev.github.io/blog/messaging-with-localbroadcastmanager/
Otto event bus where both activity and fragment classes are connected to the event bus and they activity publishes event and fragment subscribes to it. This is what I am using for something similar in my application. (But I have pretty frequent asynchronous events that come along. SO I am using this. 2nd option might be sufficient in your case).
Example for this :
http://www.vogella.com/tutorials/JavaLibrary-EventBusOtto/article.html
As ramesh already mentioned, back button handling happens in your activity class that holds the fragments. Here is a simple example, how you can handle these back button events for your fragment.
Activity Code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean returnSuperKeyDown = true;
if(keyCode == KeyEvent.KEYCODE_BACK){
Fragment fragment = getYourCurrentFragment();
if (fragment instanceof YourFragment) {
returnSuperKeyDown = ((YourFragment) fragment).onFragmentKeyDown();
}
}
if (returnSuperKeyDown) {
return super.onKeyDown(keyCode, event);
} else {
return true;
}
}
YourFragment Method:
public boolean onFragmentKeyDown() {
updateYourFragment();
return false;
}
#Rithe, #sunder sharma
As per me there is simple to refresh the fragment when come back from other fragment,
We just have to override the onActivityCreated Method for refresh fragment.
Like as
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//your code which you want to refresh
loadItems();
}
You can also update/refresh the fragment using onStart() method.
public void onStart(){
super.onStart();
//update your fragment
}
This worked fine for me.
call your loadItem() method onHiddenChanged(boolean hidden)method.onHiddenChanged is overrided method
On my app I have a ListView with Checkboxes and have an adapter that extends BaseAdapterto populate the ListView. The basic function of the list is to show debts and the user can choose which ones to pay by checking the boxes, you have the total at the bottom of the list that gets updated when the user adds/removes an item. Now, some debts are related to another and if the user checks one, any other related debt should be marked as well and same if you uncheck a debt. I also have a button that should clear all the selected debts on the list, and that's where my problem is.
I keep record of the selected debts on an ArrayList and it seems to work for all the program but the clear button. When the button is pressed the selected debts list seems to be always empty. Any idea on what could be happening?
Here is my adapter:
public class ServicesFinancialStatusAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener{
private Context context;
private List<Debts> debtsList;
private List<Debts> selectedDebts;
private LayoutInflater inflater;
private int tabPosition;
private float total;
private OnTotalChangedListener listener;
public ServicesFinancialStatusAdapter(Context context, List<Debts> debtsList, int tabPosition) {
this.context = context;
this.debtsList = debtsList;
this.tabPosition = tabPosition;
this.total = 0;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.selectedDebts = new ArrayList<Debts>();
}
#Override
public int getCount() {
return debtsList.size();
}
#Override
public Object getItem(int i) {
return debtsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.item_services_financial_status, viewGroup, false);
holder.concept = (TextView) view.findViewById(R.id.payment_concept);
holder.descriptionOrDate = (TextView) view.findViewById(R.id.payment_description_date);
holder.amount = (TextView) view.findViewById(R.id.payment_amount);
holder.expirationDate = (TextView) view.findViewById(R.id.payment_expiration_date);
if (tabPosition > 4) {
holder.checkBox = (CheckBox) view.findViewById(R.id.check_box);
holder.checkBox.setOnCheckedChangeListener(this);
}
view.setTag(holder);
} else
holder = (ViewHolder) view.getTag();
Debts item = debtsList.get(i);
holder.concept.setText(item.getConcept());
holder.amount.setText(item.getAmountToString());
if (item.isExpired())
holder.expirationDate.setText(context.getString(R.string.expired_status_indicator));
else
holder.expirationDate.setText(context.getString(R.string.debts_expiration_date_indicator) + item.getExpirationDate());
if (tabPosition < 3)
holder.descriptionOrDate.setText(item.getDescription());
else if (tabPosition < 5)
holder.descriptionOrDate.setText(item.getDate());
else {
holder.descriptionOrDate.setVisibility(View.GONE);
holder.checkBox.setVisibility(View.VISIBLE);
holder.checkBox.setTag(i);
holder.checkBox.setChecked(item.isSelected());
}
return view;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Get the position of the item clicked and the data object
Integer position = (Integer) buttonView.getTag();
Debts item = debtsList.get(position);
//Change the status ob the object
item.setSelected(isChecked);
for (Debts debts : debtsList) {
//Check on the list for related objects and marks them as well
if (debts.getConceptId() == item.getRelatedDebt())
debts.setSelected(isChecked);
//Get the amount of the debt and add/remove it from
//the selectedDebts list and update the total
float amount = debts.getAmount();
if (debts.isSelected()) {
if (!selectedDebts.contains(debts)) {
selectedDebts.add(debts);
listener.onTotalChanged(addToTotal(amount), selectedDebts);
}
}
else {
if (selectedDebts.contains(debts)) {
selectedDebts.remove(debts);
listener.onTotalChanged(removeFromTotal(amount), selectedDebts);
}
}
}
//Finally update the UI
notifyDataSetChanged();
}
//Anywhere else in the code selectedDebts has the right data but here
//Here the size of the list is always 0
public void unMarkDebts() {
for (Debts debts : debtsList) {
//Get the amount of the debt and remove it from
//the selectedDebts list, set the data object as unselected
//and update the total
float amount = debts.getAmount();
if (selectedDebts.contains(debts)) {
debts.setSelected(false);
selectedDebts.remove(debts);
listener.onTotalChanged(removeFromTotal(amount), selectedDebts);
}
}
//Update the UI
notifyDataSetChanged();
}
private float addToTotal(float value) {
return total += value;
}
private float removeFromTotal(float value) {
return total -=value;
}
public interface OnTotalChangedListener{
public void onTotalChanged(float total, List<Debts> selectedDebts);
}
public void setOnTotalChangedListener(OnTotalChangedListener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView concept, descriptionOrDate, amount, expirationDate;
CheckBox checkBox;
}
}
And here is my fragment code:
public class CheckoutFragment extends BaseFragment implements View.OnClickListener, ServicesFinancialStatusAdapter.OnTotalChangedListener {
public static final String TAG = CheckoutFragment.class.getSimpleName();
private List<Debts> debtsList;
private List<Debts> selectedDebts;
private ServicesFinancialStatusAdapter adapter;
private TextView totalView, positiveBalanceView;
private View noDebtsView, header, footer;
private LinearLayout mainLayout;
private float total, positiveBalance;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
debtsList = new ArrayList<Debts>();
adapter = new ServicesFinancialStatusAdapter(getActivity(), debtsList, 5);
adapter.setOnTotalChangedListener(this);
webServices = ((MainActivity) getActivity()).getNetworkInstance();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Initialize the views
...
reloadData();
onTotalChanged(0, null);
return view;
}
#Override
public void onClick(View view) {
reloadData();
}
#Override
public void onTotalChanged(float total, List<Debts> selectedDebts) {
this.total = total == 0 ? total : total - positiveBalance;
this.selectedDebts = selectedDebts;
totalView.setText(getString(R.string.total_indicator) + Utilities.formatNumberAsMoney(this.total));
getActivity().invalidateOptionsMenu();
}
private void reloadData() {
debtsList.clear();
adapter = new ServicesFinancialStatusAdapter(getActivity(), debtsList, 5);
adapter.setOnTotalChangedListener(this);
loadData();
}
private void loadData() {
//Load debts from server
...
}
private void saveSelectedDebts() {
for (Debts selectedDebt : selectedDebts) {
long id = Debts.insert(getActivity(), selectedDebt);
//Log.d(TAG, "Inserted " + selectedDebt.getConcept() + " with ID " + id);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (!((MainActivity) getActivity()).drawerIsOpen) {
inflater.inflate(R.menu.checkout, menu);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clear:
adapter.unMarkDebts();
break;
case R.id.checkout:
selectPaymentMode();
break;
}
return super.onOptionsItemSelected(item);
}
private void selectPaymentMode() {
...
}
}
The chat broke. I think one investigation could be:
Everytime you call reload, you are initiating from scracth the adapter with a new object, (call method new). Remove that line and just use the previous adapter (taking care of initiating the adapteer on onCreate). Notice that the vairable selectedDebts is local to the adapter and you are not passing it in the constructor.