Overflowers,
在我的项目中,我将一个带有名称和分数的JSON对象发送到servlet,该响应是一个JSON的高分榜。然后我使用GSON将列表转换为ArrayList,并将set作为我的hiscoreList在我的适配器中用于listview。这一切都正常,除非我尝试设置convertView的文本时它会给出一个nullpointer异常。
这是我的适配器代码:
public class HighscoreAdapter extends ArrayAdapter<HighscoreItem>{
public HighscoreAdapter(Context context, ArrayList<HighscoreItem> items){
super(context, 0, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
final HighscoreItem item = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.highscore_item, parent, false);
}
TextView name = (TextView) findViewById(R.id.thename);
TextView score = (TextView) findViewById(R.id.thescore);
name.setText(item.getName()); << NullPointer
score.setText(String.valueOf(item.getScore())); << NullPointer
return convertView;
}
}
我的onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_score);
ListView highscoreListView = (ListView) findViewById(R.id.list);
highscoreList = new ArrayList<HighscoreItem>();
adapter = new HighscoreAdapter(getBaseContext(), highscoreList);
highscoreListView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.sendButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendMyScore();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
我如何设置列表:
Gson gson = new Gson();
HighscoreItem[] highscoreItems = gson.fromJson(test, HighscoreItem[].class);
highscoreList.clear();
for(int i = 0; i < highscoreItems.length; i++){
highscoreList.add(highscoreItems[i]);
}
adapter.notifyDataSetChanged();
错误日志:
06-24 22:03:39.591 15162-15162/com.example.lucschuttel.infraandsec E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.lucschuttel.infraandsec, PID: 15162
java.lang.NullPointerException
at com.example.lucschuttel.infraandsec.HighScoreActivity$HighscoreAdapter.getView(HighScoreActivity.java:82)
at android.widget.AbsListView.obtainView(AbsListView.java:2738)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1274)
at android.widget.ListView.onMeasure(ListView.java:1186)
at android.view.View.measure(View.java:17495)
答案 0 :(得分:2)
您应该致电convertView.findViewById(R.id.thename);
而不仅仅是findViewById
。
如果不能解决问题,请同时发布您的xml文件。
答案 1 :(得分:2)
而不是使用
TextView name = (TextView) findViewById(R.id.thename);
TextView score = (TextView) findViewById(R.id.thescore);
使用
TextView name = (TextView) convertView.findViewById(R.id.thename);
TextView score = (TextView) convertView.findViewById(R.id.thescore);