Alex
Alex

Reputation: 81

Android App: how to display resultset in Listview?

I am new to this.... I have a connection to MySQL database and using jdbc connector. Running queries and displaying to textview no problem, but how do I display all fetched records in ListView. I went through tutorials found here and there but they describe how to do it with cursor but I have Resultset as a result of my query. Please help and Thank you

Upvotes: 0

Views: 5960

Answers (1)

ᗩИᎠЯƎᗩ
ᗩИᎠЯƎᗩ

Reputation: 2132

Once you've run your query you have your ResultSet like in this example:

sqlConnection myConn = new sqlConnection();
Statement stmt = myConn.getConnection().createStatement();
ResultSet resSet = stmt.executeQuery(myQuery);

You can now read the data step-by-step with a while and fill your LinkedList:

List<Example> mExampleList = new LinkedList<Example>();

while (resSet.next()) {
    Example mExample = new Example ();      
    mExample.ID = resSet.getInt("ExampleID");
    mExample.name = resSet.getString("ExampleName");
    [..]
    mExampleList.add(mExample);
}

Note: remember to close the connection!

The list "mExampleList" can now become the content of your adapter:

CustomAdapterOptimized mAdapter = new CustomAdapterOptimized(mContext, R.layout.example_item, mExampleList);
mListView.setAdapter(mAdapter);

That's it.


In this example I supposed you have a class named Example representing the single item; a list named ExampleList containing the items to display; a Context "mContext"; a layout "example_item" representing the view of the single item inside your list.

I am using a CustomAdapterOptimized like this one:

private class CustomAdapterOptimized extends ArrayAdapter<Example> {

public CustomAdapterOptimized(Context context, int textViewResourceId, List<Example> objects) {
    super(context, textViewResourceId, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getViewOptimize(position, convertView, parent);
}

public View getViewOptimize(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater)
            getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.example_item, null);
    viewHolder = new ViewHolder();
    viewHolder.exampleID= (TextView) convertView.findViewById(R.id.exampleID);
    viewHolder.exampleName= (TextView) convertView.findViewById(R.id.exampleName);
    convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
        Example example = (Example)getItem(position);
        viewHolder.exampleID.setText(example.ID);
        viewHolder.exampleName.setText(example.name);
        return convertView;
}

private class ViewHolder {
    public TextView exampleID;
    public TextView exampleName;
}
}

Upvotes: 2

Related Questions