android - BaseAdapter 中的 GetView 调用无限时间

标签 android listview infinite custom-lists

在应用程序中,我从 Url 加载数据并将其显示在 ListView 中。我从 Url 检索的总项目是 5 个项目,这些项目在 ListView 中成功显示。但是 getView() 在后端运行无限次。IT继续调用直到 Activity 处于 Activity 状态。我无法弄清楚为什么它调用了这么多时间。 我的代码是

public class asasa  extends Activity  {
    //ListView listView;
    Intent intent;
    public int currentimageindex=0;
    private ProgressDialog pDialog;

    //Class Declartion DataHolder
    DataHolder obj;
    Timer timer;
    TimerTask task;
    ImageView slidingimage;
    private int[] IMAGE_IDS = {
            R.drawable.myno, R.drawable.cock, R.drawable.item,
            R.drawable.ketchup,R.drawable.oil,R.drawable.pan
    };
    //ProgressDialog progressDialog;


    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();


    static final String URL = "http://10.0.2.2/android_connect/get_all_products.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";

    private static final String TAG_NAME = "name";           
    private static final String TAG_Description = "description";
    private static final String TAG_URL = "url";
    private static final String TAG_Price = "price";


    LazyAdapter adapter;
    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // products JSONArray
    JSONArray products = null;

    // Connection detector class
    ConnectionDetector cd;

    String  ITEMTITLE ="HasMapValue";



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

        cd = new ConnectionDetector(getApplicationContext());

        // get Internet status
        isInternetPresent = cd.isConnectingToInternet();
        if (isInternetPresent) {

            LoadAllProducts il = new LoadAllProducts();
            il.execute(URL);
        }
        else
        {
            // Internet connection is not present
            // Ask user to connect to Internet
            Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
        }


    }
    public void longToast(CharSequence message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }




    public class LazyAdapter extends BaseAdapter {

        private Activity activity;
        private  LayoutInflater inflater=null;
        private ArrayList<HashMap<String, Object>> data;
        int i=0;
        public LazyAdapter(Activity a, ArrayList<HashMap<String, Object>> d) {
            activity = a;
            data=d;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public int getCount() {
            return data.size();
        }

        public Object getItem(int position) {
            return position;
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            View vi=convertView;
            if(convertView==null)
                vi = inflater.inflate(R.layout.list_row, null);

            TextView title = (TextView)vi.findViewById(R.id.title); // title
            TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
            TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
            ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);

            HashMap<String, Object> song = new HashMap<String, Object>();
            song = data.get(position);

            DataHolder objj=new DataHolder();
            objj=(DataHolder) song.get(ITEMTITLE);

            Log.i("iiiiii  "," " +i++);

            Log.i("objj.GetName()  ",objj.GetName());
            Log.i("objj.GetDescription()  ",objj.GetDescription());
            Log.i("objj.GetPrice()  ",objj.GetPrice());


            title.setText(objj.GetName());
            artist.setText(objj.GetDescription());
            duration.setText(objj.GetPrice());
            imageview.setImageBitmap(objj.Getimage());



            return vi;
        }
    }






    class LoadAllProducts extends AsyncTask<String, String, String> {
        // creating new HashMap
        ArrayList<HashMap<String, Object>> productsList=new ArrayList<HashMap<String,Object>>();
        Bitmap decodedByte;
        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(asasa.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, "GET", params);

            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);
                    Log.i("products  ",products.toString());
                    // looping through All Products
                    Log.i("LENGTHHHH  "," "+products.length());
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);
                        Log.i("ccccccccc  ",c.toString());
                        // Storing each json item in variable
                        //  String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);
                        Log.i("name::",name);

                        String description = c.getString(TAG_Description);
                        Log.i("description::",description);

                        String price = c.getString(TAG_Price);
                        Log.i("price",price);

                        byte[] decodedString = Base64.decode(c.getString(TAG_URL), Base64.DEFAULT);
                        decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

                        obj=new DataHolder();
                        obj.setData(name, description, price, decodedByte);


                        HashMap<String, Object> map = new HashMap<String, Object>();



                        map.put(ITEMTITLE, obj);

                        productsList.add(map);

                    }
                } else {
                    // no products found
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            ListView list;

            // dismiss the dialog after getting all products
            list=(ListView)findViewById(R.id.list);

            adapter=new LazyAdapter(asasa.this, productsList);        
            list.setAdapter(adapter);


            // Click event for single list row
            list.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                                }
            });     

            if (pDialog.isShowing()) {
                pDialog.dismiss();
                }


        }

    }
    public void onPause()
    {
        super.onPause();


    }


    public class DataHolder 

    {
        String Name;
        String Description;
        String Price;
        Bitmap image;

        public void setData(String Name,String Descipton,String Price,Bitmap iamage)
        {
            this.Name=Name;
            this.Description=Descipton;
            this.Price=Price;
            this.image=iamage;
        }

        public String GetName()
        {return Name;}
        public String GetDescription()
        {return Description;}
        public String GetPrice()
        {return Price;}
        public Bitmap Getimage()

            {return image;}

        }
    }

和 getview()

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);

        HashMap<String, Object> song = new HashMap<String, Object>();
        song = data.get(position);

        DataHolder objj=new DataHolder();
        objj=(DataHolder) song.get(ITEMTITLE);

        Log.i("iiiiii  "," " +i++);

        Log.i("objj.GetName()  ",objj.GetName());
        Log.i("objj.GetDescription()  ",objj.GetDescription());
        Log.i("objj.GetPrice()  ",objj.GetPrice());


        title.setText(objj.GetName());
        artist.setText(objj.GetDescription());
        duration.setText(objj.GetPrice());
        imageview.setImageBitmap(objj.Getimage());



        return vi;
    }

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background" >

<include layout="@layout/footer" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="460dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/background2"
    android:minHeight="400dp"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/bar" >

        <Button
            android:id="@+id/back"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/left" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/ImageView3_Left"
            android:layout_width="200dp"
            android:layout_height="150dp"
            android:layout_gravity="center_vertical|center_horizontal"
            android:layout_marginTop="20dp" >
        </ImageView>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="10dp"
            android:background="@drawable/textarea"
            android:orientation="vertical" >

            <ListView
                android:id="@+id/list"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:divider="#b5b5b5"
                android:dividerHeight="1dp"
                android:listSelector="@drawable/list_selector" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

最佳答案

我将在这里为其他人发布答案..

使用ListView时,请确保为ListView设置固定高度,否则getView()将被多次调用。这是因为 ListView 尝试计算有多少项可以可见。

关于android - BaseAdapter 中的 GetView 调用无限时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17130366/

相关文章:

Android SignInHubActivity 在请求范围时挂起空白 View ,除了进度条

haskell - 使用延迟模态从定点运算符计算(无限)树

python - 是否有替代 python 生成器输入排列的方法?

java - while循环陷入无限循环

android - 在 android studio 上导入 Gradle 项目失败

Android - compileSDKVersion "Google Inc.:Google APIs:22"和 "22"有什么区别?

android - 如何在 android 中创建自定义启动 Activity 方法?

android - 在 Android 的两个选项卡上使用相同的 View

android - 使用 setX、setPadding 或补间动画滑动 ListView?

android - 如何知道单击的特定 ListView 项目中的哪个 View