java无法将数据加载到活动中的ListView
我使用json在Activity类中加载数据,内容如下:
我的活动课:
public class CategoryCarActivity extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<Category> carsList = new ArrayList<Category>();
JSONArray manufacturers = null;
String manufacturer_id, manufacturer_name;
private static final String URL_MANUFACTURERS = "MyURL";
// ALL JSON node names
private static final String TAG_CARS = "cars";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MANUFACTURER = "name";
private static final String TAG_PRICE = "price";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(CategoryCarActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
Intent i = getIntent();
manufacturer_id = i.getStringExtra("id");
carsList = new ArrayList<Category>();
// Loading tracks in Background Thread
new LoadTracks().execute();
// get listview
ListView lv = getListView();
/**
* Listview on item click listener
* SingleTrackActivity will be lauched by passing manufacturer id, car id
* */
lv.setOnItemClickListener(new 安卓.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// On selecting single track get car information
Intent i = new Intent(getApplicationContext(), DetailListCarActivity.class);
// to get car information
// both manufacturer id and car is needed
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Toast.makeText(getApplicationContext(), "Manufacturer Id: " + manufacturer_id + ", Car Id: " + car_id, Toast.LENGTH_SHORT).show();
i.putExtra("manufacturer_id", manufacturer_id);
i.putExtra("car_id", car_id);
startActivity(i);
}
});
}
/**
* Background Async Task to Load all tracks under one album
* */
class LoadTracks extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CategoryCarActivity.this);
pDialog.setMessage("Loading selected car ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting tracks json and parsing
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// post album id as GET parameter
params.add(new BasicNameValuePair(TAG_ID, manufacturer_id));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Category List JSON: ", json);
try {
JSONObject jObj = new JSONObject(json);
if (jObj != null) {
String manufacturer_id = jObj.getString(TAG_ID);
manufacturer_name = jObj.getString(TAG_MANUFACTURER);
manufacturers = jObj.getJSONArray(TAG_CARS);
if (manufacturers != null) {
// looping through All cars
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
// track no - increment i value
String track_no = String.valueOf(i + 1);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
// HashMap<String, String> map = new HashMap<String, String>();
Category category = new Category();
category.setManufacturer_id(manufacturer_id);
category.setId(id);
category.setName(name);
category.setPrice(price);
// adding each child node to HashMap key => value
/*
map.put("manufacturer_id", manufacturer_id); // note here
map.put(TAG_ID, car_id);
map.put("track_no", track_no + ".");
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
*/
// adding HashList to ArrayList
// carsList.add(map);
carsList.add(category);
}
} else {
Log.d("Manufacturers: ", "null");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
pDialog.dismiss();
ListAdapter adapter = new ArrayAdapter<Category>(
CategoryCarActivity.this, // the context
R.layout.list_item_categorys, // Simple list item - will toString() your data
carsList // The arraylist
);
// updating listview
setListAdapter(adapter);
}
}
}
列出项目类别。xml
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:layout_width="fill_parent"
安卓:layout_height="wrap_content" >
<TextView
安卓:id="@+id/manufacturer_id"
安卓:layout_width="fill_parent"
安卓:layout_height="wrap_content"
安卓:visibility="gone" />
<!-- Song id / Hidden by default -->
<TextView
安卓:id="@+id/car_id"
安卓:layout_width="fill_parent"
安卓:layout_height="wrap_content"
安卓:visibility="gone" />
<TextView
安卓:id="@+id/track_no"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:paddingBottom="15dip"
安卓:paddingLeft="5dip"
安卓:paddingTop="15dip"
安卓:textColor="#000000"
安卓:textSize="16dip"
安卓:layout_alignParentLeft="true"/>
<TextView
安卓:id="@+id/manufacturer_name"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:paddingBottom="15dip"
安卓:paddingLeft="5dip"
安卓:paddingTop="15dip"
安卓:textColor="#000000"
安卓:textSize="16dip"
安卓:layout_toRightOf="@+id/track_no"/>
<TextView
安卓:id="@+id/price"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentRight="true"
安卓:layout_centerVertical="true"
安卓:paddingLeft="3dip"
安卓:paddingRight="6dip"
安卓:textColor="#9ed321" />
我已经调试并检查了Logcat,看到数据已经加载,一切正常,但不知道为什么数据不能加载到ListView
更新 Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.totoroads.安卓.app, PID: 4697
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at 安卓.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:393)
at 安卓.widget.ArrayAdapter.getView(ArrayAdapter.java:369)
如何解决这个问题??谢谢!
# 1 楼答案
需要按照Ben在onPostExecute()中的建议设置列表视图
# 2 楼答案
除了Ben的答案之外,还需要在asynctask完成其后台功能后,即在asynctask的onPostExecute()方法中,将列表设置为listview适配器
# 3 楼答案
This code looks really similar。。。也许把剩下的抄下来
你需要一个数据适配器
如果你真的想定制一个布局,你也可以创建
ArrayAdapter<Category>
的子类# 4 楼答案
您没有向列表视图提供列表。您需要使用适配器将列表添加到列表视图中。本教程将帮助您完成整个过程http://www.vogella.com/tutorials/AndroidListView/article.html
在asyncTask的后期执行中,可以调用适配器。notifyDataSetChanged()。您的视图将更新为新的列表内容