自定义ListActivity with checkbox会出错

时间:2015-02-02 13:29:11

标签: android

这是我的主要活动 我有自定义ListActivity与复选框

public class MainActivity extends ListActivity {

ListView list;
Button btn1;
String url="";
private ArrayList <Product>  allProducts = new ArrayList<Product>();
private ProductAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  

    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    btn1 = (Button) findViewById(R.id.btn);
    list = getListView();   

    url="http://192.168.1.100/test/product.txt?id=";//+d.getInt("id");      

    try{
        ConnectivityManager c =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);                  
        NetworkInfo n =c.getActiveNetworkInfo();
        if (n!= null && n.isConnected()){

            Log.d("url*********",url);

            new Background().execute(url);
        }
       }catch(Exception e){}

    adapter = new ProductAdapter(getApplicationContext(),R.layout.productrow,allProducts);

setListAdapter(adapter);

getListView().setItemsCanFocus(false);

btn1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

SparseBooleanArray checked = getListView().getCheckedItemPositions();

    ArrayList<String> selectedItems = new ArrayList<String>();
    ArrayList<Integer> selectedItemsPrice = new ArrayList<Integer>();
    ArrayList<Integer> selectedItemsId = new ArrayList<Integer>();
  Log.d("**************",Integer.toString(checked.size()));

    if(checked!=null){
    for (int i = 0; i < checked.size(); i++) {

        int position = checked.keyAt(i);

        if (checked.valueAt(i))
            {
            selectedItems.add(adapter.getItem(position).getProduct_name());
            selectedItemsPrice.add(adapter.getItem(position).getProduct_price());
            selectedItemsId.add(adapter.getItem(position).getProduct_id());
            }
    }}

    int k = selectedItems.size();
    int[] outputStrArrId = new int[k];
    int[] outputStrArrPrice = new int[k];
    String[] outputStrArrItem = new String[k];

    for (int i = 0; i < k; i++) {
        outputStrArrItem[i] = selectedItems.get(i);
        outputStrArrId[i] = selectedItemsId.get(i);
        outputStrArrPrice[i] = selectedItemsPrice.get(i);
    }

    Intent intent = new Intent(getApplicationContext(), AddOrder.class);

    Bundle b = new Bundle();
    b.putStringArray("st3", outputStrArrItem);

    b.putIntArray("st1",outputStrArrId );
    b.putIntArray("st2",outputStrArrPrice );

    intent.putExtras(b);

    startActivity(intent);

    }
 });

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position, id);

    Product p = allProducts.get(position);
    if (p.isChecked()) { 
        p.setChecked(false);
        l.setItemChecked(position, false);
    } else {
        p.setChecked(true);
        l.setItemChecked(position, true);
    }

}

和我的适配器是

public class ProductAdapter extends ArrayAdapter<Product> {

private ArrayList<Boolean> itemChecked      = null;
ArrayList<Product> allProducts;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ProductAdapter (Context context , int resource ,ArrayList<Product> objects)
{
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    allProducts = objects;

}

@Override
public View getView(final int position ,View convertView,ViewGroup parent)
{
    View v = convertView;
    if(v==null)
    {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);

        holder.name = (TextView) v.findViewById(R.id.tv1);
        holder.price = (TextView) v.findViewById(R.id.price);
        holder.checkbox = (CheckBox) v.findViewById(R.id.cb1);
        v.setTag(holder);

    }

    else{
        holder = (ViewHolder) v.getTag();

    }
    holder.name.setText(allProducts.get(position).getProduct_name());
    int s = allProducts.get(position).getProduct_price();
    holder.price.setText(Integer.toString(s));

    holder.checkbox.setChecked(allProducts.get(position).isChecked());

    return v;

}

static class ViewHolder {

    public TextView name;
    public TextView price;
    public CheckBox checkbox ;

}

}

这是我的产品pojo类

 public class Product {

int product_id;

private boolean checked = false ;

    public boolean isChecked() {
    return checked;
}

public void setChecked(boolean checked) {
    this.checked = checked;
}

    String product_name;

   int product_price;

   int product_qunatity;

   int hotel_id;

public int getProduct_id() {
    return product_id;
}

public void setProduct_id(int product_id) {
    this.product_id = product_id;
}

public String getProduct_name() {
    return product_name;
}

public void setProduct_name(String product_name) {
    this.product_name = product_name;
}

public int getProduct_price() {
    return product_price;
}

public void setProduct_price(int product_price) {
    this.product_price = product_price;
}

public int getProduct_qunatity() {
    return product_qunatity;
}

public void setProduct_qunatity(int product_qunatity) {
    this.product_qunatity = product_qunatity;
}

public int getHotel_id() {
    return hotel_id;
}

public void setHotel_id(int hotel_id) {
    this.hotel_id = hotel_id;
}
}

当我检查多个菜肴并点击继续(给check.size有0值), 在进行第二次活动时,它没有给出任何结果

3 个答案:

答案 0 :(得分:0)

尝试通过此代码我有使用它可能会帮助你 布局

<ListView 
    android:id="@+id/listdata"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ></ListView>

代码.class

private ListView listdata ;
String[] values = new String[] { "Android", "iPhone"};

listdata=(ListView)findViewById(R.id.listdata);

     final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < values.length; ++i) {
          list.add(values[i]);
        }
        final StableArrayAdapter adapter = new StableArrayAdapter(this,
            android.R.layout.simple_list_item_multiple_choice, list);
        listdata.setAdapter(adapter);

}
private class StableArrayAdapter extends ArrayAdapter<String> {

    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

    public StableArrayAdapter(Context context, int textViewResourceId,
        List<String> objects) {
      super(context, textViewResourceId, objects);
      for (int i = 0; i < objects.size(); ++i) {
        mIdMap.put(objects.get(i), i);
      }
    }

    @Override
    public long getItemId(int position) {
      String item = getItem(position);
      return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
      return true;
    }

  }

答案 1 :(得分:0)

使用list的长度,而不是SparseBooleanArrray,而不是checked.size()

   for (int i = 0; i < list.getCount(); i++) 

见这里:

How to get Selected items from Multi Select List View

在这里

http://developer.android.com/reference/android/util/SparseBooleanArray.html

答案 2 :(得分:0)

除了其他观察之外,ViewHolder还有其他视图,例如TextViews和Checkboxes。您正在访问TextView并希望在其中找到一个pojo,它只有文本 您的适配器使用text加载视图 - getProgramName()返回文本。 holder.name.setText(allProducts.get(位置).getProduct_name());

要在文本视图中访问文本,请使用类似:selectedItems.add(adapter.getItem(position).getText()。toString());