我不知道如何使用ListItem重新加载我的RecyclerView。 我想做什么? 我在Android Studio中创建了一个简单的片段部分项目。在此之后,我添加了一个片段,其中包含两个按钮,另一个片段显示数据。 数据来自sqlite数据库。所以我创建了DBHelper类,它连接数据库,一个类TimeDataContent,它从数据库加载数据并将其存储在ArrayList中。 Dialog Fragment中的按钮将数据添加到数据库。 对于RecyclerView片段,我有Fragment类和RecyclerViewAdapter类(这来自android studio)。 目前,我可以向数据库添加新元素并将数据加载到RecyclerView中。 但下一步,按下按钮后更新RecyclerView并不起作用。 我从这里尝试了一些解决方案,最后一个解决方案以NullpointerException退出。
这是我的代码:
带有两个按钮的片段: 现在我在setEnterTime()中调用updateList()方法。
public class EnterExitFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private DBHelper dbHelper;
private OnFragmentInteractionListener mListener;
public EnterExitFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment EnterExitFragment.
*/
// TODO: Rename and change types and number of parameters
public static EnterExitFragment newInstance(String param1, String param2) {
EnterExitFragment fragment = new EnterExitFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
dbHelper = new DBHelper(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_enter_exit, container, false);
Button enter = (Button) view.findViewById(R.id.button_enter);
enter.setOnClickListener(this);
Button exit = (Button) view.findViewById(R.id.button_exit);
exit.setOnClickListener(this);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_enter:
setEnterTime();
break;
case R.id.button_exit:
setExitTime();
break;
}
}
private void setEnterTime() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String valnow = dateFormat.format(cal.getTime());
String text = getString(R.string.button_enter_toast) + " " +valnow;
DBHelper db = new DBHelper(getActivity());
SQLiteDatabase dbsql = db.getWritableDatabase();
ContentValues values = new ContentValues();
long id = 0;
values.put(DBHelper.FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(DBHelper.FeedEntry.COLUMN_NAME_ENTER_TIME, valnow);
values.put(DBHelper.FeedEntry.COLUMN_NAME_EXIT_TIME,"");
long newRowId;
newRowId = dbsql.insert(
DBHelper.FeedEntry.TABLE_NAME,
null,
values);
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
updateTimeList();
}
private void setExitTime() {
// get actual time
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String exitTimeNow = dateFormat.format(cal.getTime());
//String text = getString(R.string.button_exit_toast) + " " +valnow;
SQLiteDatabase dbsql = dbHelper.getReadableDatabase();
String[] projection = {
DBHelper.FeedEntry._ID,
DBHelper.FeedEntry.COLUMN_NAME_ENTER_TIME,
DBHelper.FeedEntry.COLUMN_NAME_EXIT_TIME
//DBHelper.FeedEntry.COLUMN_NAME_UPDATED
};
String sortOrder =
DBHelper.FeedEntry._ID + " DESC";
Cursor c = dbsql.query(
DBHelper.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null,//selection, // The columns for the WHERE clause
null,//selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
c.moveToFirst();
long itemId = c.getLong(c.getColumnIndexOrThrow(DBHelper.FeedEntry._ID));
String exitTimeDB = c.getString(c.getColumnIndexOrThrow(DBHelper.FeedEntry.COLUMN_NAME_EXIT_TIME));
if(exitTimeDB.equals("")){
// update time
ContentValues values = new ContentValues();
values.put(DBHelper.FeedEntry.COLUMN_NAME_EXIT_TIME, exitTimeNow);
dbsql = dbHelper.getReadableDatabase();
// Which row to update, based on the ID
String selection = DBHelper.FeedEntry._ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(itemId) };
int count = dbsql.update(
DBHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
Toast.makeText(getContext(), getString(R.string.button_exit_toast) +" "+ exitTimeNow, Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getContext(), getString(R.string.button_exit_error), Toast.LENGTH_SHORT).show();
}
}
private void updateTimeList()
{
TimeStampFragment t2 = (TimeStampFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.list); // id of RecyclerView
t2.updateTimeList();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The Fragment with the RecyclerView:
in the onCreateView() I load the data from the database (later this is asynchronous) and add it to the adapter.
public class TimeStampFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
private MyTimeStampRecyclerViewAdapter myTimeStampRecyclerViewAdapter;
private TimeDataContent timeDataContent;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TimeStampFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static TimeStampFragment newInstance(int columnCount) {
TimeStampFragment fragment = new TimeStampFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
timeDataContent=new TimeDataContent(getContext());
timeDataContent.loadData();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_timestamp_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
myTimeStampRecyclerViewAdapter = new MyTimeStampRecyclerViewAdapter(timeDataContent.getTimeItemsList(), mListener);
recyclerView.setAdapter(myTimeStampRecyclerViewAdapter);
}
return view;
}
public void updateTimeList() {
// Toast.makeText(getContext(), getString(R.string.button_exit_error), Toast.LENGTH_SHORT).show();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(TimeDataContent.TimeDataItem item);
}
}
我的适配器:
public class MyTimeStampRecyclerViewAdapter extends RecyclerView.Adapter<MyTimeStampRecyclerViewAdapter.ViewHolder> {
private final List<TimeDataContent.TimeDataItem> mValues;
private final OnListFragmentInteractionListener mListener;
public MyTimeStampRecyclerViewAdapter(List<TimeDataContent.TimeDataItem> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_timestamp, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
String id = String.valueOf(mValues.get(position).id);
holder.mIdView.setText(id);
holder.mContentView.setText(mValues.get(position).enterTime);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public TimeDataContent.TimeDataItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
即使片段中的updateTimeList()中没有代码,我也会得到NullPointerException。 我不知道什么是错的,如果是设计错误或是否有遗漏等等?
非常感谢。