DrakeZNathan DrakeZNathan - 3 months ago 20
Java Question

Calling Function From a different Class in Android Studio

This is my first time using Java and I am having a hard time calling function from a different class.

The problem I am having is with calling CmToMConversion() function from Conversion class. The program runs well but when I click on checkbox the program crashes but when I place CmToMConversion() function in the same class then the program runs. How to solve this issue. Also what is the way around if I make this function private in conversion class.

If possible answer with the code so it's easier for me to understand.

MainActivity.java


package com.example.zaid.conv;



import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
}

private void initialization()
{
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(ButttonListener);
onButtonClick();
}

private void onButtonClick()
{
Conversion mToCm = new Conversion();
onCheckbox();
EditText inputMiles = (EditText) findViewById(R.id.miles);
TextView convertedMiles = (TextView) findViewById(R.id.milesOutput);
String miles = mToCm.MilesToCmConversion(inputMiles.getText().toString());
convertedMiles.setText(miles + " cm");

Conversion inToCm = new Conversion();
EditText inputInches = (EditText) findViewById(R.id.inches);
TextView convertedInches = (TextView) findViewById(R.id.inchesOutput);
String inches = inToCm.InchesToCmConversion(inputInches.getText().toString());
convertedInches.setText(inches + " cm");

Conversion fToCm = new Conversion();
EditText inputFeet = (EditText) findViewById(R.id.feet);
TextView convertedFeet = (TextView) findViewById(R.id.feetOutput);
String feet = fToCm.FeetToCmConversion(inputFeet.getText().toString());
convertedFeet.setText(feet + " cm");
}

private void onCheckbox()
{
CheckBox check = (CheckBox) findViewById(R.id.checkBox);
check.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View change)
{
Conversion CmToM = new Conversion();
boolean check = ((CheckBox) change).isChecked();
if (check)
CmToM.CmToMConversion();
else
onButtonClick();
}
});
}

private OnClickListener ButttonListener = new OnClickListener()
{
public void onClick(View clickEvent)
{
onButtonClick();
}
};
}


Conversion.java

package com.example.zaid.conv;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

public class Conversion extends Activity {

// @Override
// protected void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
// }
//Handling Checkbox//
public void CmToMConversion()
{

EditText inputMiles = (EditText) findViewById(R.id.miles);
TextView convertedMiles = (TextView) findViewById(R.id.milesOutput);
String miles = MilesToMConversion(inputMiles.getText().toString());
convertedMiles.setText(miles + " m");

EditText inputInches = (EditText) findViewById(R.id.inches);
TextView convertedInches = (TextView) findViewById(R.id.inchesOutput);
String inches = InchesToMConversion(inputInches.getText().toString());
convertedInches.setText(inches + " m");

EditText inputFeet = (EditText) findViewById(R.id.feet);
TextView convertedFeet = (TextView) findViewById(R.id.feetOutput);
String feet = FeetToMConversion(inputFeet.getText().toString());
convertedFeet.setText(feet + " m");
}

//Conversion To Cm//
public String MilesToCmConversion(String milesToCm)
{
try
{
double mil = Double.parseDouble(milesToCm);
double cm = mil * 160934.4;
return String.format("%3.1f", cm);
}
catch (NumberFormatException exception)
{
return "0";
}
}

public String InchesToCmConversion(String inchToCm)
{
try
{
double inch = Double.parseDouble(inchToCm);
double cm = inch * 2.54;
return String.format("%3.1f", cm);
}
catch (NumberFormatException exception)
{
return "0";
}
}

public String FeetToCmConversion(String ftToCm)
{
try
{
double ft = Double.parseDouble(ftToCm);
double cm = ft * 30.48;
return String.format("%3.1f", cm);
}
catch (NumberFormatException exception)
{
return "0";
}
}

public String MilesToMConversion(String milToCm)
{
try
{
double mil = Double.parseDouble(milToCm);
double m = (mil * 160934.4) / 100;
return String.format("%3.1f", m);
}
catch (NumberFormatException exception)
{
return "0";
}
}

//Conversion To Meter//
private String InchesToMConversion(String inchToM)
{
try
{
double inch = Double.parseDouble(inchToM);
double m = (inch * 2.54) / 100;
return String.format("%3.1f", m);
}
catch (NumberFormatException exception)
{
return "0";
}
}



private String FeetToMConversion(String ftTom)
{
try
{
double ft = Double.parseDouble(ftTom);
double m = (ft * 30.48) / 100;
return String.format("%3.1f", m);
}
catch (NumberFormatException exception)
{
return "0";
}
}


}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.zaid.conv.MainActivity">

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned|numberDecimal"
android:ems="10"
android:id="@+id/miles"
android:layout_below="@+id/textView"
android:layout_alignLeft="@+id/inches"
android:layout_alignStart="@+id/inches" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Miles"
android:id="@+id/textView"
android:textSize="24dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inches"
android:id="@+id/textView2"
android:textSize="24dp"
android:layout_below="@+id/miles"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned|numberDecimal"
android:ems="10"
android:id="@+id/inches"
android:layout_below="@+id/textView2"
android:layout_alignLeft="@+id/feet"
android:layout_alignStart="@+id/feet" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feet"
android:id="@+id/textView3"
android:textSize="24dp"
android:layout_marginTop="41dp"
android:layout_below="@+id/inches"
android:layout_centerHorizontal="true" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberSigned|numberDecimal"
android:ems="10"
android:id="@+id/feet"
android:layout_below="@+id/textView3"
android:layout_centerHorizontal="true" />

<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Meters"
android:id="@+id/checkBox"
android:checked="false"
android:layout_below="@+id/feet"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert"
android:id="@+id/button"
android:layout_below="@+id/checkBox"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/milesOutput"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/inchesOutput"
android:layout_below="@+id/milesOutput"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/feetOutput"
android:layout_below="@+id/inchesOutput"
android:layout_alignLeft="@+id/inchesOutput"
android:layout_alignStart="@+id/inchesOutput" />

</RelativeLayout>

Answer

Okay so your Conversion class looks like it's just full of utility methods. Therefore, it should not be an Activity. Just change Conversion to a class with some static methods, remove the CmToMConversion() method, that should just be in your MainActivity. The MainActivity should handle manipulating its own views.

public class Conversion{

    // Removed the CmToMConversion method

    // Make methods static
    public static String MilesToCmConversion(String milesToCm){
        try{
            double mil = Double.parseDouble(milesToCm);
            double cm = mil * 160934.4;
            return String.format("%3.1f", cm);
        } catch (NumberFormatException exception){
            return "0";
        }
    }

    // Copy the rest of your methods into the class here
    // and make them static like above
}

Once you have done that, you won't need to initialize Conversion and can just call the static methods flat out with Conversion.MilesToCmConversion(whatever);. Here's a revised MainActivity:

import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
// import package.path.to.Conversion; 

public class MainActivity extends AppCompatActivity {

// Declare your instance variables here
private EditText inputMiles, inputInches, inputFeet;
private TextView convertedMiles, convertedInches, convertedFeet;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initialization();
}

private void initialization()
{
    // Setup your instance variables here
    inputMiles = (EditText) findViewById(R.id.miles);
    inputInches = (EditText) findViewById(R.id.inches);
    inputFeet = (EditText) findViewById(R.id.feet);

    convertedMiles = (TextView) findViewById(R.id.milesOutput);
    convertedInches = (TextView) findViewById(R.id.inchesOutput);
    convertedFeet = (TextView) findViewById(R.id.feetOutput);

    // Just setup your CheckBox in your init method. You call
    // onButtonClick() which would immediately do this anyway
    // I'd also just setup an OnCheckedChangeListener like this
    CheckBox check = (CheckBox) findViewById(R.id.checkBox);
    check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked) CmToMConversion();
            else onButtonClick();     
        }
     });

    Button button = (Button) findViewById(R.id.button);
    // If you're only using the onClickListener for this one button
    // just setup the listener in line rather than making an instance
    // variable of it and referencing it
    button.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
             onButtonClick();
         }
     });
    onButtonClick();
}

private void onButtonClick()
{
    String miles = Conversion.MilesToCmConversion(inputMiles.getText().toString());
    convertedMiles.setText(miles + " cm");

    String inches = Conversion.InchesToCmConversion(inputInches.getText().toString());
    convertedInches.setText(inches + " cm");

    String feet = Conversion.FeetToCmConversion(inputFeet.getText().toString());
    convertedFeet.setText(feet + " cm");
}

// This method manipulates MainActivity's views, so it should be in MainActivity
private void CmToMConversion()
{
    String miles = Conversion.MilesToMConversion(inputMiles.getText().toString());
    convertedMiles.setText(miles + " m");

    String inches = Conversion.InchesToMConversion(inputInches.getText().toString());
    convertedInches.setText(inches + " m");

    String feet = Conversion.FeetToMConversion(inputFeet.getText().toString());
    convertedFeet.setText(feet + " m");
}
}