Tigrito
Tigrito

Reputation: 43

SearchView CSV ArrayList

I just started to program for Android. I'm building this app for my internship but I'm stock with the search function.

I have a CVS file were I set the value in a ArrayList, for this I build a CSV adapter and call this adapter in my Fragment. Now everything works fine I get my list with all the values I want, the problem is the list consist of 1000 records. This is why I want to implement a searchview so that the user can search for the desire value.

Now I want when the user choose the search and starts typing the Arrylist is searched and starts to filter the possible options in the list. This way when the desire value is shown the user can select this one.

I've been trying to do this 3 days already, I know I have to do something in the onQueryTextChange and onQueryTextsubmit. But so far no luck :( Can someone help me solve this please I would really appreciate it. Tnx in advance.

    public class CSVAdapter extends ArrayAdapter<airports> {
     Context ctx;

    public CSVAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);

        //Store a reference to the Context so we can use it to load a file from Assets.
        this.ctx = context;

        //Load the data.
        loadArrayFromFile();

}

    @Override
    public View getView(final int pos, View convertView, final ViewGroup parent){

        RelativeLayout row = (RelativeLayout)convertView;
        if(null == row){
            //No recycled View, we have to inflate one.
            LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = (RelativeLayout)inflater.inflate(R.layout.departure_point_fragment, null);
        }

        TextView anameTxt = (TextView)row.findViewById(R.id.airport_name);
        TextView acityTxt = (TextView)row.findViewById(R.id.airport_city);
        TextView acountryTxt = (TextView)row.findViewById(R.id.airport_country);
        TextView icaoTxt = (TextView)row.findViewById(R.id.airport_code);

        anameTxt.setText(getItem(pos).getAname());
        acityTxt.setText(getItem(pos).getAcity());
        acountryTxt.setText(getItem(pos).getAcountry());
        icaoTxt.setText(getItem(pos).getIcao());

        return row;
        }

    private void loadArrayFromFile(){
        try {
            // Get input stream and Buffered Reader for our data file.
            InputStream is = ctx.getAssets().open("airports.csv"); 
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;

            //Read each line
            while ((line = reader.readLine()) != null) {

                //Split to separate the name from the capital
                String[] RowData = line.split(",");

                //Create a State object for this row's data.
                airports cur = new airports();
                cur.setAname(RowData[0]);
                cur.setAcity(RowData[1]);
                cur.setAcountry(RowData[2]);
                cur.setIcao(RowData[3]);
                cur.setLat(RowData[4]);
                cur.setLon(RowData[5]);
                cur.setAltitude(RowData[6]);
                cur.setTimezone(RowData[7]);
                cur.setDst(RowData[8]);

                //Add the State object to the ArrayList (in this case we are the ArrayList).
                this.add(cur);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

public class airports {

private String aname;
private String acity;
private String acountry;
private String icao;
private String lat;
private String lon;
private String altitude;
private String timezone;
private String dst;

public String getAname() {
    return aname;
}
public void setAname(String aname) {
    this.aname = aname;
}
public String getAcity() {
    return acity;
}
public void setAcity(String acity) {
    this.acity = acity;
}
public String getAcountry() {
    return acountry;
}
public void setAcountry(String acountry) {
    this.acountry = acountry;
}
public String getIcao() {
    return icao;
}
public void setIcao(String icao) {
    this.icao = icao;
}
public String getLat() {
    return lat;
}
public void setLat(String lat) {
    this.lat = lat;
}
public String getLon() {
    return lon;
}
public void setLon(String lon) {
    this.lon = lon;
}
public String getAltitude() {
    return altitude;
}
public void setAltitude(String altitude) {
    this.altitude = altitude;
}
public String getTimezone() {
    return timezone;
}
public void setTimezone(String timezone) {
    this.timezone = timezone;
}
public String getDst() {
    return dst;
}
public void setDst(String dst) {
    this.dst = dst;
}

}

public class departurePointFragment extends SherlockListFragment implements SearchView.OnQueryTextListener{ private CSVAdapter mAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.listview, container, false);

    return view;

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);                        getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSherlockActivity().getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);  
        setHasOptionsMenu(true);


        mAdapter =new CSVAdapter(getActivity(), -1);

        setListAdapter(mAdapter);
        getListView();

        setRetainInstance(true);


    }


    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        inflater.inflate(R.menu.searching, menu);
        MenuItem item = menu.findItem(R.id.menu_search);
        SearchView itemview = (SearchView) item.getActionView();

        // Execute this when searching
        itemview.setOnQueryTextListener(this);

        super.onCreateOptionsMenu(menu, inflater);



       Log.d("Nicola", "2");

    }





    @Override
    public boolean onQueryTextSubmit(String query) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onQueryTextChange(String query) {

        Log.d("Nicola", "100");


        return true;
    }

}

Upvotes: 1

Views: 1012

Answers (1)

Spinal
Spinal

Reputation: 318

Took a while to figure this out, but here it goes :)

Add this to your adapter:

ArrayList<airports> airportsArray = new ArrayList<airports>();
public ArrayList<airports> getAirportsArray()
{
    return airportsArray;
}

(you can rightclick on the ArrayList declaration, the choose Source->Generate Getters and Setters)

After reading the CSV file you can add these objects to the newly created ArrayList, changing:

this.add(cur);

to

this.add(cur);
airportsArray.add(cur);

Then in your fragment, in the onQueryTextChange method, do the following:

this.mAdapter.clear(); // This clears the existing list

// Loop through the airports
for (airports item : mAdapter.getAirportsArray())
{
  // Does the name contains what you are searching for?
  // You can add more criteria here using the || (OR) operator
  if (item.getAname().contains(query))
  {
    // If so, add it
    mAdapter.add(item);
  }
}

mAdapter.notifyDataSetChanged(); // Notify the adapter that the dataset changed
return true;

Hope that helps, good luck!

Upvotes: 1

Related Questions