有一个MainActivity
,其片段名为FragmentOne
。我在此片段中有一个项目列表,这些数据保存在我的数据库中
我从NavigationView
中的MainActivity
进行更改。.我尝试从数据库中删除所有行。它可以工作,但是在那之后我需要刷新FragmentOne,该如何刷新FragmentOne
UI?
我在updateUI
中有一个名为FragmentOne
的方法,但是如何访问该方法?当我公开该方法时,一切都会出错!
我测试了不同的方法,但是失败了..有人可以告诉我我该怎么做吗?MainActivity
:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private TabLayout tabLayout;
private ViewPager viewPager;
private Detail mDetail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////// TOOLBAR
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
///////// DRAWER
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView =
(NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener
(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_item_one:
return false;
case R.id.nav_item_two:
AlertDialog.Builder alert_delete = new AlertDialog.Builder(
MainActivity.this);
alert_delete.setTitle("Alert!");
alert_delete.setMessage(R.string.alert_delete_all);
alert_delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DetailLab.get(getApplicationContext()).deleteAllDetail();
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.getFragmentManager().beginTransaction().replace(R.id.card_view, fragmentOne)
.commit();
dialog.dismiss();
}
});
alert_delete.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert_delete.show();
return false;
..
..
case R.id.nav_item_nine:
finish();
default:
return false;
}
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是我从另一个名为
DetailLab
的类中删除数据库中所有行的方法:public void deleteAllDetail() {
mDatabase.delete(DetailTable.NAME, null, null); }
这是我的
FragmentOne
:public class FragmentOne extends Fragment {
private static final String SAVED_NUMBER_VISIBLE = "number";
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private View view;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView)
view.findViewById(R.id.detail_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true); //This will reverse the data order but not scroll the RecyclerView to the last item
layoutManager.setStackFromEnd(true); //For keeping data order same and simply scrolling the RecyclerView to the last item
mDetailRecyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null) {
mNumberVisible =
savedInstanceState.getBoolean(SAVED_NUMBER_VISIBLE);
}
updateUI();
return view;
}
@Override
public void onResume() {
super.onResume();
updateUI();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_one_layout, menu);
MenuItem numberItem = menu.findItem(R.id.show_numbers);
if (mNumberVisible) {
numberItem.setTitle(R.string.hide_numbers);
} else {
numberItem.setTitle(R.string.show_numbers);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_numbers:
mNumberVisible = !mNumberVisible;
getActivity().invalidateOptionsMenu();
updateNumbers();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateNumbers() {
DetailLab detailLab = DetailLab.get(getActivity());
int detailCount = detailLab.getDetails().size();
String number = getResources().getQuantityString
(R.plurals.number_plural, detailCount, detailCount);
if (!mNumberVisible) {
number = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(number);
}
private void updateUI() {
DetailLab detailLab = DetailLab.get(getActivity());
List<Detail> details = detailLab.getDetails();
if (details.size() == 0) {
TextView t = (TextView) view.findViewById(R.id.empty);
t.setText(R.string.empty_view);
t.setVisibility(View.VISIBLE);
} else {
TextView t = (TextView) view.findViewById(R.id.empty);
t.setVisibility(View.GONE);
}
// Toast.makeText(getContext(), "zero", Toast.LENGTH_SHORT).show();
if (mAdapter == null) {
mAdapter = new DetailAdapter(details);
mDetailRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setDetails(details);
mAdapter.notifyDataSetChanged();
}
updateNumbers();
}
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
// private TextView mDateTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
// mDateTextView = (TextView) itemView.findViewById(R.id.detail_date);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate());
}
@Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent);
}
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
getActivity());
alert.setMessage(R.string.alert);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DetailLab.get(getActivity()).deleteDetail(mDetail);
updateUI();
updateNumbers();
dialog.dismiss();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
return true;
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
@Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater =
LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
@Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
@Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(List<Detail> details) {
mDetails = details;
}
}
}
这是我
FragmentOne
的布局:<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_one_layout">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="@+id/detail_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:textAlignment="center"
android:textSize="20sp"/>
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp"
android:src="@drawable/ic_menu_add"
android:scaleType="center"
app:elevation="8dp"
app:borderWidth="0dp"
/>
我的
logcat
: FATAL EXCEPTION: main
Process: com.drgnme.listhamrah, PID: 23454
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
at com.drgnme.listhamrah.MainActivity$1$1.onClick(MainActivity.java:76)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
最佳答案
由于MainActivity中的以下代码,我认为您遇到此问题:
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.getFragmentManager().beginTransaction().replace(R.id.card_view, fragmentOne).commit();
您尝试使用
getFragmentManager()
获取片段管理器的实例,该实例调用Activity.getFragmentManager,但是您的fragmentOne
未附加到活动,因此该方法返回null并得到一个java.lang.NullPointerException
代替
fragmentOne.getFragmentManager()
直接在活动中使用getSupportFragmentManager()
。希望这可以帮助。