How can I Reuse Methods for ListViews?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 06:12:53
LeffelMania

It seems like you're doing an extraordinary amount of extra work just to give a bunch of different query options for your Cursor.

Why not have one ListActivity, with one CursorAdapter, and simply put the query in the Intent when you want to start the Activity?

I'll work on a small code example and post it here in an edit, but you're really over-thinking this it seems. All you're trying to do is display the results of a query in a ListView. The only thing that is changing is the query. Reuse everything else.

Code sample:

public class QueryDisplay extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Bundle extras = getIntent().getExtras();

        if (extras != null)
            reloadQuery(extras.getString(QUERY_KEY));

    }

    private void reloadQuery(query) {
        // Build your Cursor here.
        setAdapter(new QueryAdapter(this, cursor));
    }

    private class QueryAdapter extends CursorAdapter {

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Set up your view here
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // Create your new view here
            final View view = LayoutInflator.from(context).inflate(R.layout.your_query_list_item_layout, parent, false); 
            return view;
        }
    }
}

That's literally all the code you should need (plus the fill-ins for your custom Views and building the Cursor). Whenever you need to change the query, you just need to call reloadQuery(String query) and you're set.

Are there any similarities in the code of your extended SimpleCursorAdapter? With regards to code like getting the external storage state, you could implement a class called, for example Utils and make the methods within it static. You will more than likely need a Context or Activity passed as a parameter however.

For example this is my external storage state checker.

public static final boolean isExternalStorageAvailable() {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return true;
    } else {
        return false;
    }
}

And my network state checker.

public static final boolean isPreferedNetworkAvailable(final Context context) {
    final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(connectivityManager.getNetworkPreference());
    return networkInfo.isAvailable();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!