简体   繁体   中英

How to handle large amount of data in list view?

I am trying to implement a list view to fetch records from database. if there are less records, then there is no problem in loading. But if there are 300 records, it is taking more time to load and if user performs some operations like scrolling etc it is crashing. Now I want my list view to fetch 10 records first.After the 10 records are fetched successfully next 10 records should load while scrolling .In such a way all the records should get loaded without hanging. How to do that?

   public class CustomAdapterWishlist extends BaseAdapter  {

    private List<Model> filteredData = null;
    private LayoutInflater mInflater;

    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private Activity i;

    public CustomAdapterWishlist(Context context, List<Model> data, Activity i) {
        this.filteredData = data ;
        mInflater = LayoutInflater.from(context);
        this.i=i;
    }

    @Override
    public int getCount() {
        int i;
        if(filteredData == null) {
            i = 0;
        }
        else {
            i = filteredData.size();
        }

        return i;
    }

    @Override
    public Object getItem(int i) {
        return filteredData.get(i);
    }

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

    class ViewHolder {
        TextView name;
        //TextView date;
        TextView price;
        TextView quantity;
        TextView barcode;
        TextView description;
        TextView image_path;
        ImageView image;
        Button btn;
        LinearLayout layout;
       TextView productId,pricerange;
    }
    ViewHolder holder;

    @SuppressLint({"ViewHolder", "InflateParams"})
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        holder= new ViewHolder();

        //===================initializing identitifiers===============//
        convertView = mInflater.inflate(R.layout.row_search_iteam_wishlist, null);
        holder = new ViewHolder();
        holder.name =  convertView.findViewById(R.id.name);
        holder.price =  convertView.findViewById(R.id.price);
        holder.quantity =  convertView.findViewById(R.id.quantity);
        holder.barcode =  convertView.findViewById(R.id.barcode);
        holder.image_path =  convertView.findViewById(R.id.image_path);
        holder.image =  convertView.findViewById(R.id.image);
        holder.description =  convertView.findViewById(R.id.description);
        holder.btn =  convertView.findViewById(R.id.btn);
        holder.layout =  convertView.findViewById(R.id.layout);
        holder.productId =  convertView.findViewById(R.id.productId);
        holder.pricerange =  convertView.findViewById(R.id.pricerange);

        convertView.setTag(holder);

        //======================== setting values for listview cell====================//
        holder.name.setText(filteredData.get(position).getName());
        holder.price.setText(filteredData.get(position).getPrice());
        holder.description.setText(filteredData.get(position).getDescription());
        holder.productId.setText(filteredData.get(position).getProductId());
        holder.quantity.setText(filteredData.get(position).getQuantity());
        holder.barcode.setText(filteredData.get(position).getBarcode());
        holder.image_path.setText(filteredData.get(position).getImage_path());
        holder.pricerange.setText(filteredData.get(position).getminmax());

        final String user_id;
        FirebaseAuth mAuth = FirebaseAuth.getInstance();
        user_id = mAuth.getUid();

        final String flag = "2";

        //========================for deleting a product in whishlist=================

        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Animation myAnim = AnimationUtils.loadAnimation(i, R.anim.bounce);
                holder.btn.startAnimation(myAnim);
                db.collection("Wishlist").document(user_id).collection("ProductList")
                        .document(filteredData.get(position).getProductId()).delete()
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                Toast.makeText(i,"item deleted", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(i,whishlist.class);
                                i.startActivity(intent);

                            }
                        });

            }
        });

        // onclicks for layouts


        holder.layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(i,Details.class);
                intent.putExtra("productId",filteredData.get(position).getProductId());
                intent.putExtra("Flag",flag);
                ((Global)i.getApplication()).setProductId(filteredData.get(position).getProductId());
                i.startActivity(intent);

            }
        });

        // downloading image //

        //Glide.with(this.i).load(filteredData.get(position).getImage_path()).into(holder.image);
        try{
            Picasso.with(this.i) //Context
                    .load(filteredData.get(position).getImage_path()) //URL/FILE
                    .fit()
                    .into(holder.image);//an ImageView Object to show the loaded image;
        }
        catch (Exception ignored){

        }
        return convertView;

    }
}

1) create search_menu.xml file

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_launcher_background"
        android:title="Поиск"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always"/>
</menu>

2) In Activity override method onCreateOptionsMenu like that

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search_menu, menu);

        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        searchView.setOnQueryTextListener(this);
        return true;
    }

3) implement interface SearchView.OnQueryTextListener in your activity

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
     @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
}

To implement the WhatsApp Material SearchView with Circular Reveal, you can do it in two ways:

  1. Using libraries

    LibSearchToolbar

    MaterialSearchView

  2. Complete Implementation in code:

Start by creating a xml which has the design of the SearchView.

search.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar android:id="@+id/searchtoolbar"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:collapseIcon="@drawable/ic_arrow_back"
    app:titleTextColor="@color/colorPrimary"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorTextPrimary"/>

Next, another xml for toolbar design.

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:titleTextColor="@color/colorTextPrimary"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"/>

Include both of them in your activity using:

<include layout="@layout/toolbar"/>
    <include layout="@layout/search"
        android:visibility="gone"/>

The Java code:

public class SearchViewActivity extends AppCompatActivity {

Toolbar toolbar, searchtollbar;
Menu search_menu;
MenuItem item_search;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    setSearchtollbar();

}

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.menu_home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.action_status:
            Toast.makeText(this, "Something", Toast.LENGTH_SHORT).show();
            return true;
        case R.id.action_search:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                circleReveal(R.id.searchtoolbar,1,true,true);
            else
                searchtollbar.setVisibility(View.VISIBLE);

            item_search.expandActionView();
            return true;
        case R.id.action_settings:
            Toast.makeText(this, "Home Settings Click", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void setSearchtollbar()
{
    searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
    if (searchtollbar != null) {
        searchtollbar.inflateMenu(R.menu.menu_search);
        search_menu=searchtollbar.getMenu();

        searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                    circleReveal(R.id.searchtoolbar,1,true,false);
                else
                    searchtollbar.setVisibility(View.GONE);
            }
        });

        item_search = search_menu.findItem(R.id.action_filter_search);

        MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                // Do something when collapsed
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    circleReveal(R.id.searchtoolbar,1,true,false);
                }
                else
                    searchtollbar.setVisibility(View.GONE);
                return true;
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                // Do something when expanded
                return true;
            }
        });

        initSearchView();


    } else
        Log.d("toolbar", "setSearchtollbar: NULL");
}

public void initSearchView()
{
    final SearchView searchView =
            (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();

    // Enable/Disable Submit button in the keyboard

    searchView.setSubmitButtonEnabled(false);

    // Change search close button image

    ImageView closeButton = (ImageView) searchView.findViewById(R.id.search_close_btn);
    closeButton.setImageResource(R.drawable.ic_close);


    // set hint and the text colors

    EditText txtSearch = ((EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text));
    txtSearch.setHint("Search..");
    txtSearch.setHintTextColor(Color.DKGRAY);
    txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));


    // set the cursor

    AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
    try {
        Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
        mCursorDrawableRes.setAccessible(true);
        mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor);
    } catch (Exception e) {
        e.printStackTrace();
    }    
}


 //  This sets the Circular Reveal Animation in the Search Bar

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
    final View myView = findViewById(viewID);

    int width=myView.getWidth();

    if(posFromRight>0)
        width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
    if(containsOverflow)
        width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);

    int cx=width;
    int cy=myView.getHeight()/2;

    Animator anim;
    if(isShow)
        anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
    else
        anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);

    anim.setDuration((long)220);

    // make the view invisible when the animation is done
    anim.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            if(!isShow)
            {
                super.onAnimationEnd(animation);
                myView.setVisibility(View.INVISIBLE);
            }
        }
    });

    // make the view visible and start the animation
    if(isShow)
        myView.setVisibility(View.VISIBLE);

    // start the animation
    anim.start();
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM