游标数据未加载到列表视图中

时间:2015-04-14 10:52:32

标签: android android-fragments android-cursoradapter android-cursorloader

我编写了一个片段,用于加载来自自定义内容提供商的数据。我已经使用了google示例中的contacts sample program中的游标加载器实现。我目前面临的问题是数据没有显示,并且从下面卡在加载屏幕上。

link

这是我的片段

public class DealsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private static final String TAG = "DealsFragment";
private static final boolean DEBUG = true;

private DealsAdapter mAdapter;
private static final int LOADER_ID = 1;

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private DealInteractionListener mListener;


@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(true);
    Uri uri = DealProvider.CONTENT_URI;
    Cursor c = getActivity().getContentResolver().query(uri,null,null,null,null);
    //mAdapter = new DealCursorAdapter(getActivity(),c);
    //mAdapter = new DealListAdapter(getActivity());
    String[] columns = {DealProvider.ID,DealProvider.DEAL_DATA};
    int[] ids = {R.id.promotion_name,R.id.promotion_description};
    mAdapter = new DealsAdapter(getActivity());
    setEmptyText("No applications");
    setListAdapter(mAdapter);
    setListShown(false);

    if (DEBUG) {
        Log.i(TAG, "+++ Calling initLoader()! +++");
        if (getLoaderManager().getLoader(LOADER_ID) == null) {
            Log.i(TAG, "+++ Initializing the new Loader... +++");
        } else {
            Log.i(TAG, "+++ Reconnecting with existing Loader (id '1')... +++");
        }
    }
    getLoaderManager().initLoader(LOADER_ID, null, this);
}

public static DealsFragment newInstance(String param1, String param2) {
    DealsFragment fragment = new DealsFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */

public DealsFragment() {
}
void insertDeal(String data){
    ContentValues values = new ContentValues();
    values.put(DealProvider.DEAL_DATA, data);
    Uri uri = getActivity().getContentResolver().insert(
            DealProvider.CONTENT_URI, values);
    Log.d(TAG,"DealInserted");
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }


}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    insertDeal("Hello World");
    try {
        mListener = (DealInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}


@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    final Cursor cursor = mAdapter.getCursor();

    cursor.moveToPosition(position);
    if (null != mListener) {
        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        mListener.onDealSelected(DummyContent.ITEMS.get(position).id);
    }
}



/**********************/
/** LOADER CALLBACKS **/
/**********************/


@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    Uri uri = DealProvider.CONTENT_URI;
    return new CursorLoader(getActivity(), uri, null, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    Log.d(TAG,"Swapping with new cursor");
    mAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    mAdapter.swapCursor(null);
}




/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface DealInteractionListener {
    // TODO: Update argument type and name
    public void onDealSelected(String id);
}

private class DealsAdapter extends CursorAdapter{
    private LayoutInflater mInflater;

    public DealsAdapter(Context context) {
        super(context, null,0);
        mInflater = LayoutInflater.from(context);

    }
    private class ViewHolder {
        TextView text1;
        TextView text2;
        ImageView img;
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View itemLayout =
                mInflater.inflate(R.layout.deal_list_item, parent, false);


        final ViewHolder holder = new ViewHolder();
        holder.text1 = (TextView) itemLayout.findViewById(R.id.promotion_name);
        holder.text2 = (TextView) itemLayout.findViewById(R.id.promotion_description);
        holder.img = (ImageView) itemLayout.findViewById(R.id.imageView3);

        itemLayout.setTag(holder);
        return itemLayout;

    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final ViewHolder holder = (ViewHolder) view.getTag();
        final String data = cursor.getString(1);
        final int id = cursor.getInt(0);


        try {
            JSONObject deal = new JSONObject(data);
            String deal_name = deal.getString("deal_name");
            String deal_desc = deal.getString("deal_description");


            holder.text1.setText(deal_name);
           holder.text2.setText(deal_desc);

            String deal_url = deal.getString("deal_url");
            DownloadImageTask d = new DownloadImageTask(holder.img);
            d.execute(deal_url);



        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public Cursor swapCursor(Cursor newCursor) {
        return super.swapCursor(newCursor);
    }

    @Override
    public int getCount() {
        return super.getCount();
    }


}

和内容提供商

public class DealProvider extends ContentProvider {

static final String PROVIDER_NAME = "com.idisplay.frags.dealProvider";
static final String URL = "content://" +PROVIDER_NAME + "/deals";
public static final Uri CONTENT_URI = Uri.parse(URL);


// Creates a UriMatcher object.
//private static final UriMatcher sUriMatcher;

public static final String ID = "_id";
public static final String DEAL_DATA = "deal_data";

static final int DEALS = 1;
static final int DEALS_ID = 2;


DBHelper dbHelper;

private static HashMap<String, String> DealMap;

static final UriMatcher uriMatcher;
static{
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(PROVIDER_NAME, "deals", DEALS);
    uriMatcher.addURI(PROVIDER_NAME, "deals/#", DEALS_ID);
}

private SQLiteDatabase database;
static final String DATABASE_NAME = "myapp";
static final String TABLE_NAME = "deals";
static final int DATABASE_VERSION = 1;
static final String CREATE_TABLE =
        " CREATE TABLE " + TABLE_NAME +
                " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                " deal_data TEXT NOT NULL);";

public DealProvider() {
//    sUriMatcher = new UriMatcher(0);
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    // Implement this to handle requests to delete one or more rows.
    int count = 0;

    switch (uriMatcher.match(uri)){
        case DEALS:
            // delete all the records of the table
            count = database.delete(TABLE_NAME, selection, selectionArgs);
            break;
        case DEALS_ID:
            String id = uri.getLastPathSegment();   //gets the id
            count = database.delete( TABLE_NAME, ID +  " = " + id +
                    (!TextUtils.isEmpty(selection) ? " AND (" +
                            selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unsupported URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

@Override
public String getType(Uri uri) {
//        switch (uriMatcher.match(uri)){
//            // Get all friend-birthday records
//            case DEALS:
//                return "vnd.android.cursor.dir/vnd.example.friends";
//            // Get a particular friend
//            case DEALS_ID:
//                return "vnd.android.cursor.item/vnd.example.friends";
//            default:
//                throw new IllegalArgumentException("Unsupported URI: " + uri);
//        }
    return "";
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    long row = database.insert(TABLE_NAME, "", values);

    // If record is added successfully
    if(row > 0) {
        Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
        getContext().getContentResolver().notifyChange(newUri, null);
        return newUri;
    }
    throw new SQLException("Fail to add a new record into " + uri);
}

@Override
public boolean onCreate() {
    Context context = getContext();
    dbHelper = new DBHelper(context);
    // permissions to be writable
    database = dbHelper.getWritableDatabase();
    if(database == null)
        return false;
    else
        return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    // the TABLE_NAME to query on
    queryBuilder.setTables(TABLE_NAME);
    switch (uriMatcher.match(uri)) {
        // maps all database column names
        case DEALS:
            queryBuilder.setProjectionMap(DealMap);
            break;
        case DEALS_ID:
            queryBuilder.appendWhere( ID + "=" + uri.getLastPathSegment());
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
    }
    Cursor cursor = queryBuilder.query(database, projection, selection,
            selectionArgs, null, null, sortOrder);
    /**
     * register to watch a content URI for changes
     */
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
                  String[] selectionArgs) {
    int count = 0;

    switch (uriMatcher.match(uri)){
        case DEALS:
            count = database.update(TABLE_NAME, values, selection, selectionArgs);
            break;
        case DEALS_ID:
            count = database.update(TABLE_NAME, values, ID +
                    " = " + uri.getLastPathSegment() +
                    (!TextUtils.isEmpty(selection) ? " AND (" +
                            selection + ')' : ""), selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unsupported URI " + uri );
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

private class DBHelper extends SQLiteOpenHelper {
    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)     {
        Log.w(DBHelper.class.getName(),
                "Upgrading database from version " + oldVersion + " to "
                        + newVersion + ". Old data will be destroyed");
        db.execSQL("DROP TABLE IF EXISTS " +  TABLE_NAME);
        onCreate(db);
    }
}
}

1 个答案:

答案 0 :(得分:0)

函数setListShown(false)未显示正在加载的列表。