user6079154 user6079154 - 12 days ago 4
Java Question

Activity to Fragment error having trouble getting value to shared preferences

I'm currently developing a calorie app for my class project. I had started using a activity for the layout but my professor wants me to use a fragment instead. While trying to convert the code to fragment I came across errors and having difficulty saving the value to the shared preference. The page i'm currently working on gets information from the user and depending what the user selects determines their calories. That value is then saved in shared preference.

Thanks in advance for the help, I'm new to android studio and developing apps.

profile java file

`public class Profile extends Fragment implements View.OnClickListener {

//adaptors spinners

ArrayAdapter<String> HeightFeetAdapter;
ArrayAdapter<String> WeightLBSAdapter;


//references UI elements
Button SaveButton;

Spinner weightSpinner;
Spinner heightSpinner;
Spinner goal;
Spinner gender;
Spinner activityLevel;

EditText age;
private Animation anim;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment


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

String username =
getActivity().getIntent().getStringExtra("Username");

TextView userMain = (TextView) myView.findViewById(R.id.User);
userMain.setText(username);

age =(EditText)myView.findViewById(R.id.editText3);
age.setInputType(InputType.TYPE_CLASS_NUMBER);

heightSpinner = (Spinner) myView.findViewById(R.id.HeightSpin);

weightSpinner = (Spinner) myView.findViewById(R.id.WeightSpin);

activityLevel = (Spinner) myView.findViewById(R.id.activity_level);
ArrayAdapter<CharSequence> adapter_activity =
ArrayAdapter.createFromResource(getActivity(),
R.array.activity_level, android.R.layout.simple_spinner_item);
adapter_activity.setDropDownViewResource
(android.R.layout.simple_spinner_dropdow
n_item);
activityLevel.setAdapter(adapter_activity);

goal = (Spinner) myView.findViewById(R.id.goal);
ArrayAdapter<CharSequence> adapter_goal =
ArrayAdapter.createFromResource(getActivity(),
R.array.goal, android.R.layout.simple_spinner_item);
adapter_goal.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
goal.setAdapter(adapter_goal);

gender = (Spinner) myView.findViewById(R.id.gender);
ArrayAdapter<CharSequence> adapter_gender =
ArrayAdapter.createFromResource(getActivity(),
R.array.gender, android.R.layout.simple_spinner_item);

adapter_gender.setDropDownViewResource
(android.R.layout.simple_list_item_activated_1);
gender.setAdapter(adapter_gender);


SaveButton = (Button) myView.findViewById(R.id.savebutton);
SaveButton.setOnClickListener(this);


initializeSpinnerAdapters();
loadLBVal();
loadFTVal();

anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
heightSpinner.startAnimation(anim);

anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
weightSpinner.startAnimation(anim);


anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fading);
SaveButton.startAnimation(anim);

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



return myView;
}






public void loadLBVal() {
weightSpinner.setAdapter(WeightLBSAdapter);
// set the default lib value
weightSpinner.setSelection(WeightLBSAdapter.getPosition("170"));
}


// load the feets value range to the height spinner
public void loadFTVal() {
heightSpinner.setAdapter(HeightFeetAdapter);
// set the default value to feets
heightSpinner.setSelection(HeightFeetAdapter.getPosition("5\"05'"));
}


public void initializeSpinnerAdapters() {

String[] weightLibs = new String[300];
// loading spinner values for weight
int k = 299;
for (int i = 1; i <= 300; i++) {
weightLibs[k--] = String.format("%3d", i);
}
// initialize the weightLibsAdapter with the weightLibs values
WeightLBSAdapter = new ArrayAdapter<String>(getContext(),
R.layout.activity_spinner_item, weightLibs);

WeightLBSAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);


String[] heightFeets = new String[60];
// loading values 3"0' to 7"11' to the height in feet/inch
k = 59;
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 12; j++) {
heightFeets[k--] = i + "\"" + String.format("%02d", j) + "'";
}
}
// initialize the heightFeetAdapter with the heightFeets values

HeightFeetAdapter = new ArrayAdapter<String>(getContext(),

R.layout.activity_spinner_item, heightFeets);

HeightFeetAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);


}



@Override
public void onClick(View v) {

switch (v.getId()) {

case R.id.savebutton:


int activityLevel, goal, gender, age;
// Get preferences
float height = getSelectedHeight();
float weight = getSelectedWeight();


activityLevel =
((Spinner)getActivity().findViewById
(R.id.activity_level)).getSelectedItemPosition();


goal = ((Spinner)getActivity().
findViewById(R.id.goal)).getSelectedItemPosition();

gender= ((Spinner)getActivity().
findViewById(R.id.gender)).getSelectedItemPosition();


age = Integer.parseInt(((EditText).
getActivity().findViewById(R.id.editText3)));




int tdee = calculateTDEE(height,weight,activityLevel,age,gender,
goal);

// Save preferences in XML
SharedPreferences userInfo = getSharedPreferences("userInfo",
0);
SharedPreferences.Editor editor = userInfo.edit();
editor.putInt("tdee", tdee);
editor.commit();
try {
FileOutputStream fileos = new FileOutputStream ( new
File(getFilesDir() + "userData.xml"));
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "TDEE");
xmlSerializer.text(Integer.toString(tdee));
xmlSerializer.endTag(null, "TDEE");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

break;
}
}


public float getSelectedWeight() {
String selectedWeightValue = (String)weightSpinner.getSelectedItem();

return (float) (Float.parseFloat(selectedWeightValue) * 0.45359237);


}



public float getSelectedHeight() {
String selectedHeightValue = (String)heightSpinner.getSelectedItem();

// the position is feets and inches, so convert to meters and return
String feets = selectedHeightValue.substring(0, 1);
String inches = selectedHeightValue.substring(2, 4);
return (float) (Float.parseFloat(feets) * 0.3048) +
(float) (Float.parseFloat(inches) * 0.0254);

}



public int calculateTDEE(float height, float weight, int activityLevel,
int
age, int gender, int goal) {

double bmr = (10 * weight) + (6.25 * height) - (5 * age) + 5;
if(gender == 1) {
bmr = (10* weight) + (6.25 * height) - (5*age) - 161;
}
double activity = 1.25;
switch(activityLevel) {
case 1:
activity = 1.375;
break;
case 2:
activity = 1.55;
break;
case 3:
activity = 1.725;
break;
case 4:
activity = 1.9;
break;
}
double tdee = bmr * activity;
switch(goal) {
case 0:
tdee -=500;
break;
case 2:
tdee +=500;
break;
}
tdee += .5;
return (int) tdee;
}
















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

}


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

}

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

}


`

fragment_profile xml

`

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

android:orientation="vertical"

android:background="@drawable/imgbackground2"
android:weightSum="1">
<TextView
android:layout_width="180dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/emptyString"
android:id="@+id/User"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="@+id/tv_main_title" />
<TextView
android:layout_width="294dp"
android:layout_height="65dp"
android:text="Please Complete Information"
android:textColor="@color/colorBackground"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:textSize="20dp" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Age"
android:id="@+id/textView12"
android:layout_above="@+id/gender"
android:layout_alignLeft="@+id/textView5"
android:layout_alignStart="@+id/textView5" />

<EditText
android:layout_width="50dp"
android:layout_height="50dp"
android:inputType="number"
android:ems="10"
android:id="@+id/editText3"
android:imeOptions="actionDone"
android:layout_alignTop="@+id/gender"
android:layout_alignLeft="@+id/editText"
android:layout_marginLeft="0dp"
android:layout_column="1" />
</TableRow>

</TableLayout>


<RelativeLayout
android:layout_width="194dp"
android:layout_height="26dp"></RelativeLayout>


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="@+id/textView11"
/>

<Spinner
android:layout_width="113dp"
android:layout_height="40dp"
android:id="@+id/gender"
android:layout_above="@+id/textView5"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignStart="@+id/textView4"
android:layout_alignEnd="@+id/textView3"
android:spinnerMode="dropdown"
android:popupBackground="@color/colorBackground" />

<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="329dp"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="@string/weightLabel"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/colorBackground"
android:textSize="25dp"
android:paddingRight="0dp"
android:paddingLeft="-2dp" />

<Spinner
android:id="@+id/WeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="@string/weightLabel"
android:spinnerMode="dropdown"
android:layout_weight="2"
android:textAlignment="center"
android:popupBackground="@drawable/graybackground2"

android:layout_span="2"
android:layout_column="1" />

</TableRow>

<TableRow
android:id="@+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="15dp" >

</TableRow>



<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="@string/heightLabel"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/colorBackground"
android:textSize="25dp"
android:layout_column="0"
android:layout_marginLeft="5dp" />

<Spinner
android:id="@+id/HeightSpin"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:prompt="@string/heightLabel"
android:layout_weight="2"
android:popupBackground="@drawable/graybackground2"

android:spinnerMode="dropdown"
android:layout_marginTop="0dp"
android:layout_margin="0dp"
android:layout_marginBottom="0dp"
android:layout_column="1"
android:paddingTop="0dp"
android:paddingBottom="0dp"
android:textAlignment="center"
android:paddingStart="5dp"
android:layout_marginLeft="0dp"
android:layout_span="0"
android:layout_marginRight="0dp" />


</TableRow>

<TableRow>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Activity Level"
android:id="@+id/textView7"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />

<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="@+id/activity_level"
android:layout_below="@+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp" />

</TableRow>

<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Goal"
android:id="@+id/textView8"
android:layout_below="@+id/activity_level"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp" />

<Spinner
android:layout_width="200dp"
android:layout_height="50dp"
android:id="@+id/goal"
android:layout_below="@+id/textView8"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:spinnerMode="dropdown" />
</TableRow>
</TableLayout>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/savebutton"
android:radius="10dp"
android:textColor="@color/colorBackground"
android:onClick="saveAction"
android:layout_alignParentBottom="true"
android:layout_toEndOf="@+id/editText3"
android:layout_gravity="right" />


</LinearLayout>



`

Here are is a screenshot of the errors I'm current getting.
enter image description here

Answer

You can use getContext() or getActivity() before the functions you want to invoke. getContext().getSharedPreferences(), getContext().getFilesDir(), etc.