自定义适配器listview无法运行Android

时间:2017-04-26 16:15:23

标签: java android listview baseadapter custom-adapter

自定义适配器存在问题。我无法显示listview。当我运行应用程序时它停止运行。 请看下面的代码。

提前谢谢

AllProductsActivity.java

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);



    // Hashmap for ListView
    productsList = new ArrayList<>();
productitems=new ArrayList<String>();


    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    pitems=new ArrayList<>();
    ListView lv=(ListView) findViewById(R.id.list);

    lv.setAdapter(myCustomAdapter);
    // on seleting single product
    // launching Edit Product Screen



}


// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String price = c.getString(TAG_PRICE);
                    String av = c.getString(TAG_AV);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value

                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_PRICE,price);
                    map.put(TAG_AV, av);
                    productitems.add(id);
                    productitems.add(name);
                    productitems.add(price);
                    productitems.add(av);

                    pitems.add(productitems);
                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        NewCActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products

        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */

                myCustomAdapter=new MyCustomAdapter(AllProductsActivity.this, pitems);



            }
        });

    }

}

}

MyCustomAdapter.java

 public class MyCustomAdapter extends BaseAdapter {

 private Context context_;
private ArrayList<ArrayList<String>> productitems;





private int quantity = 1;



public MyCustomAdapter(Context context, ArrayList<ArrayList<String>> productitems) {


   this.productitems=productitems;
    this.context_ = context;


}

@Override
public int getCount() {
    return productitems.size();
}

@Override
public Object getItem(int position) {
    return productitems.get(position).get(0);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context_.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        convertView = mInflater.inflate(R.layout.list_item, null);
    }

    TextView id = (TextView) convertView.findViewById(R.id.pid);
    TextView name = (TextView) convertView.findViewById(R.id.name);
    TextView price = (TextView) convertView.findViewById(R.id.price);
    TextView av = (TextView) convertView.findViewById(R.id.av);
    Button plus = (Button) convertView.findViewById(R.id.plus);
    Button minus = (Button) convertView.findViewById(R.id.minus);
    TextView qnt = (TextView) convertView.findViewById(R.id.quantity_text_view);
    Button add = (Button) convertView.findViewById(R.id.add);
    String pid = productitems.get(position).get(0);
    String pname =  productitems.get(position).get(1);
    String pprice = productitems.get(position).get(2);
    String pav = productitems.get(position).get(3);
    Integer pqnt;
    id.setText(pid);
    name.setText(pname);
    price.setText(pprice);
    av.setText(pav);

    plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
            quantity = quantity + 1;

            TextView quantityTextView = (TextView) v.findViewById(R.id.quantity_text_view);
            quantityTextView.setText("" + quantity);

            notifyDataSetChanged();
        }
    });
    minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
            quantity = quantity - 1;
            TextView quantityTextView = (TextView) v.findViewById(R.id.quantity_text_view);
            quantityTextView.setText("" + quantity);
            notifyDataSetChanged();
        }
    });
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
            quantity = quantity - 1;
            TextView quantityTextView = (TextView) v.findViewById(R.id.quantity_text_view);
            quantityTextView.setText("" + quantity);
            notifyDataSetChanged();
        }
    });


    return convertView;
}

}

日志

FATAL EXCEPTION: main
                                                                            Process: com.example.stratos.fastsupply, PID: 11074
                                                                            java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stratos.fastsupply/com.example.stratos.fastsupply.AllProductsActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                                at android.os.Looper.loop(Looper.java:193)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5333)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                             Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
                                                                                at android.app.ListActivity.onContentChanged(ListActivity.java:243)
                                                                                at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:344)
                                                                                at android.app.Activity.setContentView(Activity.java:1948)
                                                                                at com.example.stratos.fastsupply.AllProductsActivity.onCreate(AllProductsActivity.java:57)
                                                                                at android.app.Activity.performCreate(Activity.java:5343)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429) 
                                                                                at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342) 
                                                                                at android.os.Handler.dispatchMessage(Handler.java:110) 
                                                                                at android.os.Looper.loop(Looper.java:193) 
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5333) 
                                                                                at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                                at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
                                                                                at dalvik.system.NativeStart.main(Native Method) 

XML

>     <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
>     android:layout_width="fill_parent"
>     android:layout_height="fill_parent"
>     android:orientation="vertical"
>     android:weightSum="1"
>     android:baselineAligned="false">
>     <!-- Main ListView
>          Always give id value as list(@android:id/list)
>     -->
> 
>     <SearchView
>         android:layout_width="match_parent"
>         android:layout_height="wrap_content"
>         android:layout_weight="0.1">
>     </SearchView>
> 
>     <TextView
>         android:id="@+id/textView"
>         android:layout_width="match_parent"
>         android:layout_height="30sp"
> 
>         android:text="Product Name     Price      Qnt"
>         android:layout_weight="0.1"/>
> 
>     <ListView
>         android:id="@+id/list"
>         android:layout_width="fill_parent"
>         android:layout_height="347sp"
>         android:layout_weight="0.60" />
> 
>     <Button
>         android:id="@+id/sendOrder"
>         android:layout_width="match_parent"
>         android:layout_height="50sp"
>         android:background="#ffff8800"
>         android:fontFamily="sans-serif-smallcaps"
>         android:text="Send Order"
>         android:textColorLink="@color/colorAccent"
>         android:textSize="20sp"
>         android:layout_weight="0.2"/>
> 
> 
> </LinearLayout>

2 个答案:

答案 0 :(得分:0)

发生此问题是因为Listview中的ID错误,请将ListView窗口小部件更改为:

 <ListView
         android:id="@android:id/list"
         android:layout_width="fill_parent"
         android:layout_height="347sp"
         android:layout_weight="0.60" />

答案 1 :(得分:-2)

参考。

public class yourAdapter extends ArrayAdapter<Actors> {

LayoutInflater vi;
ViewHolder holder;
int resource;
private final Activity context;
private final ArrayList<Actors> details;

public WifiAdapter(Activity context, int resource , ArrayList<Actors> details) {
super(context, resource, details);
vi =  (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.resource = resource;
this.details = details;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
    holder = new ViewHolder();
    v = vi.inflate(resource, null);
    holder.Type = (TextView) v.findViewById(R.id.type);
    .......//your remaining code
    v.setTag(holder);
}
else {
    holder =(ViewHolder) v.getTag();
}


holder.Name.setText(details.get(position).getType());
..........//ur remaining code 


return v;
}

static class ViewHolder {
public TextView Type;
//your remaing code
}
}