Aug 19, 2014

how to display list of objects in android listview

public class Part {
   
    String PartNum;  
    String PartDesc;
   
    // constructors
    public Part() {

    }   

    public Part(int idx,String PartNum, String PartDesc) {
       
        this.PartNum = PartNum;
        this.PartDesc = PartDesc;
    }
    public Part(String PartNum, String PartDesc) {       
        this.PartNum = PartNum;
        this.PartDesc = PartDesc;
    }
    // setter
  
    public void setPartNum(String PartNum) {
        this.PartNum = PartNum;
    }
    public void setPartDesc(String PartDesc) {
        this.PartDesc = PartDesc;
    }

    // getter
    public String getPartNum() {
        return this.PartNum;
    }
    public String getPartDesc() {
        return this.PartDesc;
    }
}
Now that we have our class defined, let's create the layout that will be used to display the individual list item, which is a simple RelativeView with an ImageView for the icon and a TextView for the label:
Create res/layout/row_cust.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
Create Display Adapter
package adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.example.mobilesalesapp.R;

import model.Part;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PartListAdapter extends ArrayAdapter<Part> {
   
    Activity context;
    List<Part> lstObject;
    public ArrayList<Part> arraylist;
    private SparseBooleanArray mSelectedItemsIds;
   
    public PartListAdapter(Activity context, int resId, List<Part> lstObject) {
        super(context, resId, lstObject);
        mSelectedItemsIds = new SparseBooleanArray();
        this.context = context;
        this.lstObject = lstObject;
       
        this.arraylist = new ArrayList<Part>();
        this.arraylist.addAll(lstObject);
    }

    private class ViewHolder {
        TextView CustID;
        TextView CustName;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.row_cust, null);
            holder = new ViewHolder();
            // Locate the TextViews in listview_item.xml
            holder.CustID = (TextView) convertView.findViewById(R.id.textView1);
            holder.CustName = (TextView) convertView.findViewById(R.id.textView2);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Part obj = getItem(position);
      
        holder.CustID.setText(obj.getPartNum());
        holder.CustName.setText(obj.getPartDesc());
        /*
        convertView
        .setBackgroundColor(mSelectedItemsIds.get(position) ? context.getResources().getColor(android.R.color.holo_purple)
                : Color.TRANSPARENT);
        */
        convertView.setBackgroundColor(mSelectedItemsIds.get(position)? 0x9934B5E4: Color.TRANSPARENT);       
        // Listen for ListView Item Click
       
        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
              
               
                Intent intent = new Intent();
                intent.putExtra("PartNum",(arraylist.get(position).getPartNum()));
                //Toast.makeText(context, lstObject.get(position).getPartNum(), Toast.LENGTH_LONG).show();
                context.setResult(Activity.RESULT_OK, intent);     
                context.finish();
            }
        });
       
        return convertView;
    }
   
    @Override
    public void add(Part obj) {
        lstObject.add(obj);
        notifyDataSetChanged();
        Toast.makeText(context, lstObject.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void remove(Part object) {
        // super.remove(object);
        lstObject.remove(object);
        notifyDataSetChanged();
    }

    public List<Part> getList() {
        return lstObject;
    }

    public void toggleSelection(int position) {
        selectView(position, !mSelectedItemsIds.get(position));
    }

    public void removeSelection() {
        mSelectedItemsIds = new SparseBooleanArray();
        notifyDataSetChanged();
    }

    public void selectView(int position, boolean value) {
        if (value)
            mSelectedItemsIds.put(position, value);
        else
            mSelectedItemsIds.delete(position);

        notifyDataSetChanged();
    }

    public int getSelectedCount() {
        return mSelectedItemsIds.size();
    }

    public SparseBooleanArray getSelectedIds() {
        return mSelectedItemsIds;
    }
   
 // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        lstObject.clear();
        if (charText.length() == 0) {
            lstObject.addAll(arraylist);
        } else {
            for (Part wp : arraylist) {
                if (wp.getPartDesc().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    lstObject.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
}
Using what you created
package com.example.mobilesalesapp;



import helper.EndlessScrollListener;
import helper.MessageBox;

import java.util.List;

import model.OrderDetail;
import model.Part;
import adapter.PartListAdapter;
import adapter.WebServicesAdapter;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class SearchPart extends Activity {
    // Database Helper
    WebServicesAdapter servicesAdapter;
    PartListAdapter adapter;
    ListView lvSearch;
    Button btnSearch;
    EditText txtSearchValue;
    Cursor cursor;
    List<Part> arraylist;
    OrderDetail objdtl = new OrderDetail();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try   
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_search_part);
           
       
            txtSearchValue= (EditText)findViewById(R.id.txtSearchValue);
           
           
            lvSearch = (ListView)findViewById(R.id.listView1);
            lvSearch.setSelected(true);
            lvSearch.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            /*     
            lvSearch.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                   
                     Intent intent = new Intent();
                     // Pass all data
                     String PartNum = adapter.arraylist.get(position).getPartNum();
                     intent.putExtra("PartNum",PartNum);              
                     Toast.makeText(SearchPart.this,PartNum, Toast.LENGTH_LONG).show();                
                    setResult(RESULT_OK, intent);     
                    finish();
                }
            });
            */       
           
            String filter= txtSearchValue.getText().toString();
            LoadPart(filter);      
            lvSearch.setOnScrollListener(new EndlessScrollListener() {
                @Override
                public void onLoadMore(int page, int totalItemsCount) {
                        // Triggered only when new data needs to be appended to the list
                        // Add whatever code is needed to append new items to your AdapterView
                    if(totalItemsCount>=20)
                    {
                        String filter= txtSearchValue.getText().toString();
                        LoadMorePart(totalItemsCount,filter);
                    }
                }
                });
           
            btnSearch = (Button)findViewById(R.id.button1);
            btnSearch.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {                   
                    String filter= txtSearchValue.getText().toString();
                    LoadPart(filter);
                }
            });
       
            // Capture Text in EditText
//                txtSearchValue.addTextChangedListener(new TextWatcher()
//                {
//       
//                    @Override
//                    public void afterTextChanged(Editable arg0) {
//                        // TODO Auto-generated method stub
//                        String text = txtSearchValue.getText().toString().toLowerCase(Locale.getDefault());
//                        adapter.filter(text);
//                    }
//       
//                    @Override
//                    public void beforeTextChanged(CharSequence arg0, int arg1,
//                            int arg2, int arg3) {
//                        // TODO Auto-generated method stub
//                    }
//       
//                    @Override
//                    public void onTextChanged(CharSequence arg0, int arg1, int arg2,
//                            int arg3) {
//                        // TODO Auto-generated method stub
//                }
//            });
           
           
        }
        catch(Exception e)
        {
            Log.e("ERROR", "ERROR IN "+e.toString());
            MessageBox.ShowError(this, e.toString());
        }
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search_part, menu);
        getMenuInflater().inflate(R.menu.menu_cancel, menu);
        return true;
    }
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {      
        case R.id.action_Cancel:      
            Intent intent = new Intent();            
            setResult(RESULT_CANCELED, intent);     
            finish();
            return true;    
        default:
            return super.onOptionsItemSelected(item);
        }
    }
   
    private void LoadPart(String filterValue) {
       
        servicesAdapter = new WebServicesAdapter(this);   
        arraylist = servicesAdapter.GetPart(1,20,filterValue);
        // Pass results to ListViewAdapter Class
        adapter = new PartListAdapter(this,R.layout.row_cust, arraylist);
        // Binds the Adapter to the ListView
        lvSearch.setAdapter(adapter);
    }
    private void LoadMorePart(int itemCount,String filterValue) {
        try
        {   
            servicesAdapter = new WebServicesAdapter(this);   
            int start = 1;
            int end =20;
            int rowCount = itemCount;
            String filter = filterValue;
            if(rowCount!=0)
            {
                start = rowCount+1;
                end = itemCount+20;
            }
            List<Part> loadMore = servicesAdapter.GetPart(start,end,filter);
            if(loadMore.size()>0)
            {
                arraylist.addAll(loadMore);
            }
            adapter.notifyDataSetChanged();
        }
        catch(Exception e)
        {          
            Log.e("ERROR", "ERROR IN "+e.toString());           
        }
    }

}

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib