0

I know it's probably very simple, but my app is not working. I need to input weight in Edittext and use its value, and the total distance value from the method CalculateDistance and the value of the CalculateCalories method. With this code, I'm not able to click on Start Button. Where do I have to add code which gets the value from Edittext and how can I make it work?

My code currently looks like this:

public class RunningModeFragment extends Fragment implements IGPSActivity
{

    MyLocation myLocation=null;
    Button btnRunningModeStart=null;
    EditText txtWeight=null;
    TextView txtTotalDistance=null;
    TextView txtCalories=null;
    Button btnShowRunningHistory = null;

    String weight;
    Float weightInKg;
    Float caloriesBurned;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.running_mode_fragment, container, false);
    }

    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        txtTotalDistance=(TextView) getView().findViewById(R.id.txtTotalDistance);
        txtWeight=(EditText) getView().findViewById(R.id.txtWeight);
        txtCalories=(TextView) getView().findViewById(R.id.txtCalories);
        if (txtWeight.getText().toString().isEmpty())
        {
            return;
        }
        else {
            weight = txtWeight.getText().toString();
            weightInKg = Float.parseFloat(weight);
        }

        btnRunningModeStart = (Button) getView().findViewById(R.id.btnRunningModeStart);
        btnRunningModeStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                onClick_StartRunningMode(v);
            }
        });

        btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
        btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onClick_ShowRunningHistory(v);
            }
        });

    }

    private void onClick_ShowRunningHistory(View v) {

        Fragment fragment = new RunningHistoryFragment();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment, "Running History");
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction.commit();
    }


    private void onClick_StartRunningMode(View v)

    {
        if(myLocation ==null)
        {
            new Thread(new Runnable() {
                public void run() {

                    DatabaseFacade dbfacade = new DatabaseFacade(getView().getContext());
                    Activity activity = new Activity(ActivityMode.RUNNING);
                    activity.setActivityId(activity.getActivityId());
                    activity.setStart(new Timestamp(new Date().getTime()));
                    dbfacade.saveActivity(activity);

                }
            }).start();


            Toast.makeText(this.getActivity(), "Start Running mode", Toast.LENGTH_SHORT).show();
            myLocation = new MyLocation();
            myLocation.LocationStart(this);
            btnRunningModeStart.setText("Stop");
        }

        else
        {
            Toast.makeText(this.getActivity(), "Stop Running mode", Toast.LENGTH_SHORT).show();
            myLocation.LocationListenerStop();
            myLocation = null;
            btnRunningModeStart.setText("Start");
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
    }


    Location lastPoint = null;
    float totalDistance = 0;

    public static float CalculateDistance(Location startPoint, Location endPoint)
    {
        return (startPoint.distanceTo(endPoint) / ((float)1000));
    }

    public static float CalculateCalories(float a, float b){
        return ((float)1.036)*a*b;
    }



    @Override
    public void locationChanged(Location location)
    {
        try
        {

            if(lastPoint==null)lastPoint = location;

            totalDistance += CalculateDistance(lastPoint, location);

            lastPoint=location;
            txtTotalDistance.setText(totalDistance + " km");
            caloriesBurned=CalculateCalories(totalDistance,weightInKg);
            txtCalories.setText(caloriesBurned + " kcal");

            DatabaseFacade dbf = new DatabaseFacade(getView().getContext());
            Activity activity = new Activity(ActivityMode.RUNNING);
            dbf.saveLocation(new GpsLocation(activity.getActivityId(), location.getLongitude(), location.getLatitude(), location.getAccuracy()));
        }catch (Exception E)

        {
            E.printStackTrace();
        }
    }


    public void onResume(){
        super.onResume();
        ((Main) getActivity()).setActionBarTitle("Running mode");
        NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.nav_view);
        //  navigationView.setNavigationItemSelectedListener((Main) getActivity());
        navigationView.setCheckedItem(R.id.runningMode);

    }
}

I need to do the following: get the value from EditText txtWeight, parse it to float and use in CalculateCalories method

  public static float CalculateCalories(float a, float b){
        return ((float)1.036)*a*b;
    }

I tried with this, but it's not working

  if (txtWeight.getText().toString().isEmpty())
    {
        return;
    }
    else {
        weight = txtWeight.getText().toString();
        weightInKg = Float.parseFloat(weight);
    }
Janeeee
  • 1
  • 2
  • What error do you get, when you click on the start button? And which line in your code does the stacktrace point to? – kalabalik Jan 17 '18 at 09:46
  • it doesn't show me any errors, without this couple lines (weight, weightinkg,calculate calories) program works fine,clicking on button is possible, it show me messages and calculates distance, but when I add these lines, I can't do anything – Janeeee Jan 17 '18 at 09:52
  • Instead of using getView() use view in your onViewCreated() – Skizo-ozᴉʞS ツ Jan 17 '18 at 09:53

4 Answers4

0

first of all create a view than initialize textview inside onCreateView like this,

View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
Textview tv= view.findViewById(R.id.tv);

the code your have written in onViewCreated() should be in onCreateVIew(). remove it from onViewCreated().

jitendra purohit
  • 652
  • 5
  • 18
0

You can put it on your onCreateView() as @jitendra purohit told to you, as follows :

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.fg_unapproved_leave, container, false);
        txtTotalDistance=(TextView) view.findViewById(R.id.txtTotalDistance);
        txtWeight=(EditText) view.findViewById(R.id.txtWeight);
        txtCalories=(TextView) view.findViewById(R.id.txtCalories);
        ...
        return view;
    }

Or you can keep your code in your onViewCreated() but instead of getView() you can do getActivity() something like this :

public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        txtTotalDistance=(TextView) getActivity().findViewById(R.id.txtTotalDistance);
        txtWeight=(EditText) getActivity().findViewById(R.id.txtWeight);
        txtCalories=(TextView) getActivity().findViewById(R.id.txtCalories);
        ...

See this question/answers aswell...

You can do that in an onClick() or if you do want to show the changes dynamically use TextWatcher.

  1. Using TextWatchers

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            if (txtWeight.getText().toString().isEmpty()) {
                return;
            }
            else {
                weight = txtWeight.getText().toString();
                weightInKg = Float.parseFloat(weight);
                //Call your CalculateCalories method
            }
        }
    };
    

    }

  2. Using onClick I'm not going to implement it, but you can do it with a Button or on the same EditText and do the same stuff that in afterChangedText() on TextWatcher.

Remember in onCreateView() you'll have to do this :

txtWeight.addTextChangedListener(textWatcher);
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

Put that line ==> weight = txtWeight.getText().toString(); in the onCLick method

btnShowRunningHistory = (Button) getView().findViewById(R.id.btnShowRunningHistory);
    btnShowRunningHistory.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (txtWeight.getText().toString().isEmpty())
              {
                  return;
              }
         else {
                  weight = txtWeight.getText().toString();
                  weightInKg = Float.parseFloat(weight);
              }
            onClick_ShowRunningHistory(v);
        }
    });
0
*If you are using View binding*

Add this line under onViewCreated

val binding=<BindingFile>.bind(<binding.root from onCreate View>)
and try accessing values now using local binding variable.


 override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        binding = FragmentSigninBinding.inflate(layoutInflater, container, false)
        val udata = "don't have a account ?"
        val content = SpannableString(udata)
        content.setSpan(UnderlineSpan(), 0, udata.length, 0)
        binding.textView5.text = content
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val root = FragmentSigninBinding.bind(binding.root)
//        Navigate to signup fragment
        binding.signup.setOnClickListener {
            view.findNavController().navigate(R.id.action_signin_to_signup)

        }
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 27 '21 at 21:01