mardi 3 mai 2016

How to clear a listview and database when clicking a button. So the user can input new information

I'm developing an app for my class project which is due this week. The issue I'm having trouble with is when the user clicks the button to clear"reset" the listview and database. The weird thing is , it does it when I click it but when I go to another activity and come back to the home page where the listview is located the items are still their and not deleted. I even created a function to delete the items from the listview and database but it seems it doesnt work. Any suggestions ? what I could do to delete it. I want the user to be able to delete all the items in the listview and database so the calories remain can also reset.

Thank you so much! Hope I made sense.

fragmenthome.java

              public class FragmentHome extends  Fragment implements 
              View.OnClickListener  {


              private TextView caloriesTotal;

              private TextView caloriesRemain;

              private ListView listView;
              private LinearLayout mLayout;



             ImageButton AddEntrybtn;
             ImageButton ResetEntry;
             Context context;

             int goalCalories;
             int totalCalorie;



              //Database
           private DatabaseHandler dba;

          private ArrayList<Food> dbFoods = new ArrayList<>();
          private CustomListViewAdapter foodAdapter;
          private Food myFood ;



                 //fragment
       private android.support.v4.app.FragmentManager fragmentManager;
       private FragmentTransaction fragmentTransaction;

       public FragmentHome() {
      // Required empty public constructor
      }




          @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {

     View myView = inflater.inflate(R.layout.fragment_home, container, 
    false);





     AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);

     AddEntrybtn.setOnClickListener(new View.OnClickListener() {
       @Override
      public void onClick(View arg0) {


           ((appMain) getActivity()).loadSelection(4);

         }
       });



      ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);

      ResetEntry.setOnClickListener(new View.OnClickListener() {
      @Override
       public void onClick(View arg0) {

           //reset data

                reset();

           }
        });



           caloriesTotal = (TextView) 
           myView.findViewById(R.id.tv_calorie_amount);

          caloriesRemain = (TextView) 
          myView.findViewById(R.id.calorieRemain);




             listView = (ListView) myView.findViewById(R.id.ListId);

             SharedPreferences prefs = 
            PreferenceManager.getDefaultSharedPreferences(getActivity());
            PreferenceManager.setDefaultValues(getActivity(),   
            R.xml.activity_preference, false);

           goalCalories =   Integer.parseInt(prefs.getString
           ("prefs_key_daily_calorie_amount", "2000"));  


           refreshData();


          return myView;


         }


             public void reset () throws SQLException {

            //

             if(foodAdapter!= null) {
             foodAdapter.clear();
            dbFoods.clear();
            listView.setAdapter(foodAdapter);// !!!!!!!
            listView.invalidateViews();


            foodAdapter.notifyDataSetChanged();
        }

     }




         public void refreshData (){

           dbFoods.clear();

           dba = new DatabaseHandler(getActivity());

           ArrayList<Food> foodsFromDB = dba.getFoods();

           totalCalorie = dba.totalCalories();

                int CaloriesLeft = 
        loadPrefs("\"@string/prefs_key_daily_calorie_amount\""
       ,totalCalorie);


       String formattedCalories = Utils.formatNumber(totalCalorie);
       String formattedRemain = Utils.formatNumber(goalCalories - 
      totalCalorie);


        //setting the editTexts:


     caloriesTotal.setText("Total Calories: " + formattedCalories);

    caloriesRemain.setText(formattedRemain);




                SharedPreferences prefs = 
   PreferenceManager.getDefaultSharedPreferences(getContext());
   PreferenceManager.setDefaultValues(getActivity(), 
    R.xml.activity_preference, false);




      goalCalories = 
    Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount", 
   "2000"));




    //Loop
    for (int i = 0; i < foodsFromDB.size(); i ++){

    String name = foodsFromDB.get(i).getFoodName();
    String date = foodsFromDB.get(i).getRecordDate();
    int cal = foodsFromDB.get(i).getCalories();
    int foodId = foodsFromDB.get(i).getFoodId();

    Log.v("Food Id", String.valueOf(foodId));

    myFood= new Food();
    myFood.setFoodId(foodId);
    myFood.setFoodName(name);
    myFood.setCalories(cal);
    myFood.setRecordDate(date);

    dbFoods.add(myFood);
   }
    dba.close();

       //setting food Adapter:
      foodAdapter = new CustomListViewAdapter(getActivity(),  
      R.layout.row_item,dbFoods);
      listView.setAdapter(foodAdapter);
       foodAdapter.notifyDataSetChanged();
     }





          //save prefs
          public void savePrefs(String key, int value) {
      SharedPreferences sharedPreferences =  
     PreferenceManager.getDefaultSharedPreferences(getContext());
     SharedPreferences.Editor editor = sharedPreferences.edit();
     editor.putInt(key, value);
     editor.apply();
     }
     //get prefs
    public int loadPrefs(String key, int value) {
    SharedPreferences sharedPreferences = 
    PreferenceManager.getDefaultSharedPreferences(getContext());
    return sharedPreferences.getInt(key, value);
    }




    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle username = getActivity().getIntent().getExtras();



   String username1 = username.getString("Username");

    TextView userMain= (TextView) getView().findViewById(R.id.User);

    userMain.setText(username1);


      }




        @Override
        public void onDetach() {
        super.onDetach();

       startActivity( new Intent(getContext(),MainActivity.class));
        }


          @Override
          public void onClick(View v) {
          switch (v.getId()) {
          case R.id.AddItems:

           AddEntry addEntry    = new AddEntry();

           fragmentTransaction = fragmentManager.beginTransaction();
           fragmentTransaction.addToBackStack(null);
           fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                .commit();


           break;

          case R.id.action_settings:

          Intent preferenceScreenIntent = new Intent(getContext(),
          PreferenceScreenActivity.class);
          startActivity(preferenceScreenIntent);

           break;

        }
    }
  }

Aucun commentaire:

Enregistrer un commentaire