我一直试图将listView填充到一个活动上,但我的listView保持为null,即使在初始化之后也是如此。我检查了错误日志并通过调试器运行它,我得出结论,我没有正确初始化它,虽然我不确定在哪里。
MainActivity
avItem.asset.metadata[titleIndex]
适配器
public class DisplayCountryActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_country);
// Construct the data source
ArrayList<Country> countries = new ArrayList<>();
// Create the adapter to convert the array to views
//context=this;
listView = (ListView) findViewById(R.id.list_view);
Cursor cursor = getContentResolver().query(Contract.Country.contentUri, null, null, null, null);
while(cursor.moveToNext()) {
countries.add(new Country(cursor.getString(cursor.getColumnIndex("country")),cursor.getDouble(cursor.getColumnIndex("capital")),
cursor.getString(cursor.getColumnIndex("area")),cursor.getInt(cursor.getColumnIndex("population")),cursor.getString(cursor.getColumnIndex("official_lang"))));
}
CountryAdaptor adapter = new CountryAdaptor(this, countries);
// Attach the adapter to a ListView
listView.setAdapter(adapter);
}
}
列表视图
public class CountryAdaptor extends ArrayAdapter<Country> {
private static LayoutInflater inflater = null;
public CountryAdaptor(Context context, ArrayList<Country> users) {
super(context, 0, users);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Country country = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = inflater.inflate(R.layout.country_item, parent, false);
}
// Lookup view for data population
TextView countryTv = (TextView) convertView.findViewById(R.id.dp_country);
TextView capitalTv = (TextView) convertView.findViewById(R.id.dp_capital);
TextView areaTv = (TextView) convertView.findViewById(R.id.dp_area);
TextView populationTv = (TextView) convertView.findViewById(R.id.dp_population);
TextView officialLanguageTv = (TextView) convertView.findViewById(R.id.dp_official_language);
// Populate the data into the template view using the data object
countryTv.setText(country.getCountry());
capitalTv.setText(country.getCapital());
areaTv.setText(country.numberToString(country.getArea()));
populationTv.setText(country.numberToString(country.getArea()));
officialLanguageTv.setText(country.getOfficial_lang());
// Return the completed view to render on screen
return convertView;
}
}
答案 0 :(得分:0)
所以我解决了这个问题。首先,为了清除空气,当我尝试使用我的xml文件初始化时,列表视图变量为null。我的错误是我将listview xml文件作为独立文件,没有格式化。所以基本上我的错误是没有将ListView标签放在我正在使用的内容xml文件中。我所要做的就是将ListView标记添加到我的内容xml文件