gpt4 book ai didi

java - Activity to Fragment 错误,无法获取共享首选项的值

转载 作者:行者123 更新时间:2023-12-02 03:12:24 25 4
gpt4 key购买 nike

我目前正在为我的类项目开发一个卡路里应用程序。我已经开始使用 Activity 进行布局,但我的教授希望我改用 fragment 。在尝试将代码转换为 fragment 时,我遇到了一些难以将值保存到共享首选项 xml 的问题。我当前正在开发的页面从用户那里获取信息,并根据用户的选择确定他们的卡路里。然后,该值将保存在共享首选项中,并显示在主 Activity 中。

提前感谢您的帮助,我是 android studio 和开发应用程序的新手。

配置文件java文件

`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();


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>

`

Fragmenthome.java

   import java.util.ArrayList;



public class FragmentHome extends Fragment implements
View.OnClickListener {


private TextView caloriesTotal;

private TextView caloriesRemain;

private ListView listView;
private LinearLayout mLayout;

private Animation anim;

ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;

int goalCalories;
int totalCalorie;



Button mButton;

//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);



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"));



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(this);







refreshData();



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

return myView;


}




public void reset () {

//


dbFoods.clear();

dba = new DatabaseHandler(getActivity());

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


//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.clear();

dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();

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



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


}



public void refreshData (){




dbFoods.clear();

dba = new DatabaseHandler(getActivity());

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

totalCalorie = dba.totalCalories();




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();

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

}


//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 onResume() {
super.onResume();



}

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

}

@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;


case R.id.ResetEntry:


reset();
anim= AnimationUtils.loadAnimation(getActivity(),
R.anim.fading);
listView.startAnimation(anim);
break;


}


}
}

偏好.xml

    <PreferenceScreen     
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory android:title="User Settings">
<EditTextPreference
android:title="Daily Calorie Amount"
android:inputType="number"
android:defaultValue="2000"
android:key="@string/prefs_key_daily_calorie_amount"
android:summary="@string/prefs_description_daily_calorie_amount" />




</PreferenceCategory>



</PreferenceScreen>

最佳答案

您可以在要调用的函数之前使用 getContext()getActivity()getContext().getSharedPreferences()getContext().getFilesDir()

关于java - Activity to Fragment 错误,无法获取共享首选项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40836592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com