【发布时间】:2014-11-28 19:20:54
【问题描述】:
我创建了一个演示应用程序来在屏幕上显示产品列表。产品列表来自远程服务器。在日志中,我可以看到数据传入并存储在 arralist 中,但不知何故,它没有与列表视图绑定。我正在使用异步类在后台进行 http 调用。
下面是创建代码的活动
ListAdapter adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dbtest2_all_products);
Log.i("Entrey level=","entere dbtest2allproducts class");
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = new ListView(DBtest2AllProducts.this);
// updating listview
lv.setAdapter(adapter);
下面是
的postexecute方法 protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// ((BaseAdapter) adapter).notifyDataSetChanged();
Log.i("before adapter",productsList.toString());
adapter = new SimpleAdapter(
DBtest2AllProducts.this, productsList,
R.layout.activity_dbtest2_list_items, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
//setAdapter(adapter);
虽然我相信 setAdapter(adapter) 步骤存在一些同步问题,但由于我是 android 新手,所以不能打赌。我尝试使用 postexecute 方法调用 setAdapter(adapter) 方法和 adapter.notifyDataSetChanged() 但它们都抛出错误说“没有为这种类型定义方法”但是如果我将适配器转换为 (BaseAdapter) 那么 adapter.notifyDataSetChanged() 不会'不要抛出任何错误,但我实际上不知道这种铸造有什么区别,而且铸造也不起作用。
下面是日志猫
I/before adapter(32729): [{pid=1, name=iphone 4s}, {pid=2, name=samsung}]
如果您发现代码有任何问题,请提出建议。感谢您提前提供帮助。
下面是xml布局
all_product.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
list_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:paddingTop="20dip"
android:paddingLeft="10dip"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>
【问题讨论】:
-
移动 lv.setAdapter(adapter);在 onPostExecute 之后,adapter = new SimpleAdapter(...
-
我试过了,但它抛出错误“lv 无法解析”我认为 lv 超出了后执行方法的范围。
标签: android listview adapter listadapter