我正在尝试插入一个从我的SQLite数据库中填充的GridView,但是我收到了错误
"尝试调用虚方法' android.view.View android.view.View.findViewById(int)'在null对象引用"
MyAdapter.java 类
public class MyAdapter extends BaseAdapter {
Context context;
ArrayList<Players> playerList;
private static LayoutInflater inflater = null;
public MyAdapter(Context context, ArrayList<Players> playerList){
this.context = context;
this.playerList = playerList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return playerList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.layout_grid_item, null);
TextView idTextView = (TextView) convertView.findViewById(R.id.tv_player_id);
TextView nameTextView = (TextView) convertView.findViewById(R.id.tv_player_name);
TextView roleTextView = (TextView) convertView.findViewById(R.id.tv_player_role);
Players p = new Players();
p = playerList.get(position);
idTextView.setText("ID " + String.valueOf(p.getId()));
nameTextView.setText("Name " + String.valueOf(p.getName()));
roleTextView.setText("Role " + String.valueOf(p.getRole()));
return convertView;
}
}
GameActivity.java 类
public class GameActivity extends Activity {
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
db = new DatabaseHelper(this);
}
public void FragmentOneClick(View view) {
Fragment myfragment;
myfragment = new RolesFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_switch, myfragment);
fragmentTransaction.commit();
}
}
RolesFragment.java
public class RolesFragment extends Fragment {
GridView gridView;
ArrayList<Players> playersList;
MyAdapter adapter;
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_viewroles, container, false);
gridView = (GridView) getView().findViewById(R.id.gv_players);
DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
playersList = new ArrayList<Players>();
playersList = databaseHelper.getPlayers();
adapter = new MyAdapter(getActivity(), playersList);
gridView.setAdapter(adapter);
return view;
}
}
答案 0 :(得分:2)
问题是getView()
返回null。
在片段中你必须使用:fragment&#39; s view
实例。
所以代替:
gridView = (GridView) getView().findViewById(R.id.gv_players);
使用:
gridView = (GridView) view.findViewById(R.id.gv_players);