我正在开发卡路里应用程序,用户可以从列表视图中删除项目。
问题:当用户点击该项目时,它会转到卡路里详细信息活动,当他们点击删除时,它会返回到主页片段。一旦我点击添加另一个条目,它就会崩溃。此外,当它回到片段主页时,看起来不一样的卡路里详细信息活动是将片段置于家中而不是完全取代它。
calorieDetails.java
public class CalorieDetails extends AppCompatActivity {
private TextView foodName, calories, dateTaken;
private Button shareButton;
private int foodId;
private Button deleteButton;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_details);
foodName = (TextView) findViewById(R.id.detsFoodName);
calories = (TextView) findViewById(R.id.detscaloriesValue);
dateTaken = (TextView) findViewById(R.id.detsDateText);
deleteButton = (Button) findViewById(R.id.deleteButton);
Food food = (Food) getIntent().getSerializableExtra("userObj");
foodName.setText(food.getFoodName());
calories.setText(String.valueOf(food.getCalories()));
dateTaken.setText(food.getRecordDate());
foodId = food.getFoodId();
foodName.setTextColor(Color.WHITE);
dateTaken.setTextColor(Color.WHITE);
calories.setTextSize(34.9 f);
calories.setTextColor(Color.WHITE);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO: put delete functionality here
android.support.v7.app.AlertDialog.Builder alert = new
android.support.v7.app.AlertDialog.Builder(CalorieDetails.this);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this item?");
alert.setNegativeButton("No", null);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHandler dba = new
DatabaseHandler(getApplicationContext());
dba.deleteFood(foodId);
Toast.makeText(CalorieDetails.this, "Food Item
Deleted!", Toast.LENGTH_SHORT).show();
FragmentHome homeFragment = new FragmentHome();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder,
homeFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
}
});
alert.show();
}
});
}
}
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;
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();
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();
}
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();
}
//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();
break;
}
}
activity_calorie_details.xml
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/FragmentHolder"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
tools:context=".CalorieDetails"
android:background="@drawable/imgbackground2"
style="@style/AppTheme">
<ImageView
android:id="@+id/logo"
android:src="@drawable/weight"
android:layout_centerHorizontal="true"
android:layout_width="180dp"
android:layout_height="180dp" />
<LinearLayout
android:id="@+id/layout"
android:elevation="4dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/logo"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/detsFoodName"
android:elevation="4dp"
android:text="dkdad"
android:textSize="19sp"
android:textStyle="bold"
android:layout_marginTop="18dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/detsCaloriesTitle"
android:text="Calories:"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/detscaloriesValue"
android:text="200"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/detsDateText"
android:text="Consumed on..."
android:textStyle="italic"
android:textSize="14sp"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/deleteButton"
android:text="DELETE"
android:textColor="#ffff"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:background="@color/colorBackground2"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Home_fragment.xml
<FrameLayout
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:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="@drawable/imgbackground2"
style="@style/AppTheme"
tools:context="layout.HomeFragment"
android:id="@+id/HomeFragment">
<RelativeLayout
android:layout_width="match_parent"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="271dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome,"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="85dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/emptyString"
android:id="@+id/User"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tv_main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="24dp"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="@string/activity_text_calorie_title"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tv_calorie_amount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
tools:text="1600"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_below="@+id/tv_main_title"
android:layout_alignParentStart="true"
android:gravity="center"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/AddItems"
android:background="?android:attr/selectableItemBackground"
android:src="@drawable/add"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:layout_below="@+id/tv_calorie_amount"
android:layout_alignParentEnd="true" />
<TextView
tools:text="1600"
android:id="@+id/calorieRemain"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_below="@+id/tv_main_title"
android:layout_toEndOf="@+id/textView" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ResetEntry"
android:background="?android:attr/selectableItemBackground"
android:src="@drawable/removecircle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:paddingRight="0dp"
android:layout_alignBottom="@+id/AddItems"
android:layout_toStartOf="@+id/AddItems" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="274dp"
android:layout_gravity="center_horizontal|bottom">
<ListView
android:id="@+id/ListId"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:dividerHeight="2dp"
android:divider="#212121"
android:scrollingCache="false"
android:smoothScrollbar="false"
android:layout_below="@+id/tv_calorie_amount"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"></ListView>
</LinearLayout>
</FrameLayout>
以下是点击删除后发生的事情的屏幕截图:
http://www.tiikoni.com/tis/view/?id=c0939b3
以下是删除项目之前Home Fragment的样子: http://www.tiikoni.com/tis/view/?id=70e433d
单击卡路里详细信息片段上的删除时logcat
05-04 02:25:25.561 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: mSContextService =
android.hardware.scontext.ISContextService$Stub$Proxy@14b764b
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@42e6828
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@42e6828
05-04 02:25:25.581 5830-5830/com.example.treycoco.calorietracker
E/ViewRootImpl: sendUserActionEvent() mView == null
单击“删除”后单击“添加条目” logcat的:
05-04 02:28:04.761 5830-
5830/com.example.treycoco.calorietracker E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 5830
java.lang.ClassCastException
com.example.treycoco.calorietracker.CalorieDetails cannot be cast
to com.example.treycoco.calorietracker.appMain
at com.example.treycoco.calorietracker.
FragmentHome$1.onClick(FragmentHome.java:118)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)