当前位置: 首页>>代码示例>>Java>>正文


Java ContentResolver.bulkInsert方法代码示例

本文整理汇总了Java中android.content.ContentResolver.bulkInsert方法的典型用法代码示例。如果您正苦于以下问题:Java ContentResolver.bulkInsert方法的具体用法?Java ContentResolver.bulkInsert怎么用?Java ContentResolver.bulkInsert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在android.content.ContentResolver的用法示例。


在下文中一共展示了ContentResolver.bulkInsert方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: loadInBackground

import android.content.ContentResolver; //导入方法依赖的package包/类
@Override
public Boolean loadInBackground() {
    Log.d(TAG, "loadInBackground() called");
    ContentResolver contentResolver = getContext().getContentResolver();
    Uri uri = DbUtils.getTableUri(MessageModel.MessagesDb.class);
    Cursor query = contentResolver.query(uri, null, null, null, null);
    if (query == null || query.getCount() == 0) {
        Log.d(TAG, "loadInBackground: no data");
        List<MessageModel> data = createData();

        ContentValues[] values = new ContentValues[data.size()];

        for (int i = 0; i < data.size(); i++) {
            values[i] = data.get(i).toContentValues();
        }

        int count = contentResolver.bulkInsert(uri, values);
        Log.d(TAG, "loadInBackground() inserted: " + count);

    }
    if (query != null) {
        query.close();
    }

    return true;
}
 
开发者ID:IstiN,项目名称:android-training-2017,代码行数:27,代码来源:MessagesLoader.java

示例2: addToPlaylist

import android.content.ContentResolver; //导入方法依赖的package包/类
public static void addToPlaylist(Context context, long[] ids, long playlistid) {
    if (ids == null) {
        Log.e("MusicBase", "ListSelection null");
    } else {
        int size = ids.length;
        ContentResolver resolver = context.getContentResolver();
        String[] cols = new String[]{"count(*)"};
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        int base = cur.getInt(0);
        cur.close();
        int numinserted = 0;
        for (int i = 0; i < size; i += 1000) {
            makeInsertItems(ids, i, 1000, base);
            numinserted += resolver.bulkInsert(uri, sContentValuesCache);
        }
    }
}
 
开发者ID:reyanshmishra,项目名称:Rey-MusicPlayer,代码行数:20,代码来源:MusicUtils.java

示例3: addToPlaylist

import android.content.ContentResolver; //导入方法依赖的package包/类
public static void addToPlaylist(@NonNull final Context context, @NonNull final List<Song> songs, final int playlistId, final boolean showToastOnFinish) {
    final int size = songs.size();
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + MediaStore.Audio.Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cursor = null;
    int base = 0;

    try {
        try {
            cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                base = cursor.getInt(0) + 1;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        int numInserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000)
            numInserted += resolver.bulkInsert(uri, makeInsertItems(songs, offSet, 1000, base));

        if (showToastOnFinish) {
            Toast.makeText(context, context.getResources().getString(
                    R.string.inserted_x_songs_into_playlist_x, numInserted, getNameForPlaylist(context, playlistId)), Toast.LENGTH_SHORT).show();
        }
    } catch (SecurityException ignored) {
    }
}
 
开发者ID:aliumujib,项目名称:Orin,代码行数:35,代码来源:PlaylistsUtil.java

示例4: addToPlaylist

import android.content.ContentResolver; //导入方法依赖的package包/类
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + "play_order" + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    int base = 0;

    try {
        cursor = resolver.query(uri, projection, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            base = cursor.getInt(0) + 1;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    int numinserted = 0;
    for (int offSet = 0; offSet < size; offSet += 1000) {
        makeInsertItems(ids, offSet, 1000, base);
        numinserted += resolver.bulkInsert(uri, mContentValuesCache);
    }
    final String message = context.getResources().getQuantityString(
            R.plurals.NNNtrackstoplaylist, numinserted, numinserted);
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
 
开发者ID:Vinetos,项目名称:Hello-Music-droid,代码行数:33,代码来源:MusicPlayer.java

示例5: addToPlaylist

import android.content.ContentResolver; //导入方法依赖的package包/类
/**
 * @param context    The {@link Context} to use.
 * @param ids        The id of the song(s) to add.
 * @param playlistid The id of the playlist being added to.
 */
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + Playlists.Members.PLAY_ORDER + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    int base = 0;

    try {
        cursor = resolver.query(uri, projection, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            base = cursor.getInt(0) + 1;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    int numinserted = 0;
    for (int offSet = 0; offSet < size; offSet += 1000) {
        makeInsertItems(ids, offSet, 1000, base);
        numinserted += resolver.bulkInsert(uri, mContentValuesCache);
    }
    final String message = context.getResources().getQuantityString(
            R.plurals.num_tracks_toplaylist, numinserted, numinserted);
    Toast.makeText((Activity) context, message, Toast.LENGTH_SHORT).show();
    playlistChanged();
}
 
开发者ID:komamj,项目名称:KomaMusic,代码行数:39,代码来源:MusicUtils.java

示例6: caseEnergyUseDay

import android.content.ContentResolver; //导入方法依赖的package包/类
/**
 * Caso de teste -  Consumo de Energia no Dia:
 *  - Incluir uma simulação da utilização 24KWH no dia 01/01/2015.
 *  - Realizar um consulta e testar os seguintes resultados:
 *    - Data Inicio : 01/01/2015
 *    - Duração: 24Hs
 *    - KWH : 24.00
 */
@Test
public void caseEnergyUseDay() {
    Context context = InstrumentationRegistry.getTargetContext();
    ContentResolver contentResolver = context.getContentResolver();
    Calendar dateBegin  =  Calendar.getInstance();
    //Utilização de energia no dia 01/01/2015.
    dateBegin.set(2015,1,1,0,0,0);
    dateBegin.set(Calendar.MILLISECOND,0);
    Calendar endDate = Calendar.getInstance();
    endDate.setTime(OhaHelper.getDateEnd(dateBegin.getTime(), false));
    Calendar beginHour = Calendar.getInstance();
    beginHour.setTime(dateBegin.getTime());
    //Realizar a inclusão:
    while (beginHour.before(endDate)){
        ContentValues[] contentValues = new ContentValues[360];
        for(int index = 0; index < contentValues.length; index++ ) {
            long id = Long.parseLong(String.format("%s%s%06d", OhaHelper.getStrDate(beginHour.getTime()), OhaHelper.getStrHour(beginHour.getTime()), index));
            //Gerar um consuno de 1000 Watts a cada 10 segundos.
            contentValues[index] = EnergyUseLogEntry.parse(
                    beginHour.getTime(),
                    10,
                    220.00,
                    400.00,
                    400.00,
                    200.00
            );
            beginHour.add(Calendar.MILLISECOND, 10000);
        }
        contentResolver.bulkInsert(
                CONTENT_URI_LOG,
                contentValues);

    }
    //Realizar a Consulta:
    String selection = String.format("%s BETWEEN ? AND ?", EnergyUseLogEntry._ID);
    String[] selectionArgs = new String[]{
            String.valueOf(OhaHelper.getDateBegin(endDate.getTime()).getTime()),
            String.valueOf(endDate.getTime().getTime())
    };
    Cursor cursor = context.getContentResolver().query(
            OhaEnergyUseContract.CONTENT_URI_DAYS,
            null,
            selection,
            selectionArgs,
            null
    );

    assertTrue("Energy Logs is empty!", cursor.moveToFirst());
    long longBeginDate = cursor.getLong(EnergyUseLogEntry.INDEX_COLUMN_CALC_DATE);
    assertEquals("Begin Date", dateBegin.getTime().getTime(), longBeginDate);
    Double duration = cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_DURATION_SUN);
    assertEquals("Duration", DateUtils.DAY_IN_MILLIS / 1000.00, duration, 0.00);
    Double totalKWH = OhaHelper.convertWhToKWH(cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_WH_TOTAL_SUN));
    assertEquals("Total KWH", "24.00", OhaHelper.formatNumber(totalKWH,"#0.00"));
}
 
开发者ID:brolam,项目名称:OpenHomeAnalysis,代码行数:64,代码来源:OhaEnergyUseProviderTest.java

示例7: syncWeather

import android.content.ContentResolver; //导入方法依赖的package包/类
/**
     * Performs the network request for updated weather, parses the JSON from that request, and
     * inserts the new weather information into our ContentProvider. Will notify the user that new
     * weather has been loaded if the user hasn't been notified of the weather within the last day
     * AND they haven't disabled notifications in the preferences screen.
     *
     * @param context Used to access utility methods and the ContentResolver
     */
    synchronized public static void syncWeather(Context context) {

//      COMPLETED (3) Within syncWeather, fetch new weather data

        try {
            /*
             * The getUrl method will return the URL that we need to get the forecast JSON for the
             * weather. It will decide whether to create a URL based off of the latitude and
             * longitude or off of a simple location as a String.
             */
            URL weatherRequestUrl = NetworkUtils.getUrl(context);

            /* Use the URL to retrieve the JSON */
            String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);

            /* Parse the JSON into a list of weather values */
            ContentValues[] weatherValues = OpenWeatherJsonUtils
                    .getWeatherContentValuesFromJson(context, jsonWeatherResponse);

            /*
             * In cases where our JSON contained an error code, getWeatherContentValuesFromJson
             * would have returned null. We need to check for those cases here to prevent any
             * NullPointerExceptions being thrown. We also have no reason to insert fresh data if
             * there isn't any to insert.
             */
            if (weatherValues != null && weatherValues.length != 0) {
                /* Get a handle on the ContentResolver to delete and insert data */
                ContentResolver sunshineContentResolver = context.getContentResolver();

//              COMPLETED (4) If we have valid results, delete the old data and insert the new
                /* Delete old weather data because we don't need to keep multiple days' data */
                sunshineContentResolver.delete(
                        WeatherContract.WeatherEntry.CONTENT_URI,
                        null,
                        null);

                /* Insert our new weather data into Sunshine's ContentProvider */
                sunshineContentResolver.bulkInsert(
                        WeatherContract.WeatherEntry.CONTENT_URI,
                        weatherValues);
            }

            /* If the code reaches this point, we have successfully performed our sync */

        } catch (Exception e) {
            /* Server probably invalid */
            e.printStackTrace();
        }
    }
 
开发者ID:fjoglar,项目名称:android-dev-challenge,代码行数:58,代码来源:SunshineSyncTask.java

示例8: syncWeather

import android.content.ContentResolver; //导入方法依赖的package包/类
/**
 * Performs the network request for updated weather, parses the JSON from that request, and
 * inserts the new weather information into our ContentProvider. Will notify the user that new
 * weather has been loaded if the user hasn't been notified of the weather within the last day
 * AND they haven't disabled notifications in the preferences screen.
 *
 * @param context Used to access utility methods and the ContentResolver
 */
synchronized public static void syncWeather(Context context) {


    try {
        /*
         * The getUrl method will return the URL that we need to get the forecast JSON for the
         * weather. It will decide whether to create a URL based off of the latitude and
         * longitude or off of a simple location as a String.
         */
        URL weatherRequestUrl = NetworkUtils.getUrl(context);

        /* Use the URL to retrieve the JSON */
        String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);

        /* Parse the JSON into a list of weather values */
        ContentValues[] weatherValues = OpenWeatherJsonUtils
                .getWeatherContentValuesFromJson(context, jsonWeatherResponse);

        /*
         * In cases where our JSON contained an error code, getWeatherContentValuesFromJson
         * would have returned null. We need to check for those cases here to prevent any
         * NullPointerExceptions being thrown. We also have no reason to insert fresh data if
         * there isn't any to insert.
         */
        if (weatherValues != null && weatherValues.length != 0) {
            /* Get a handle on the ContentResolver to delete and insert data */
            ContentResolver sunshineContentResolver = context.getContentResolver();

            /* Delete old weather data because we don't need to keep multiple days' data */
            sunshineContentResolver.delete(
                    WeatherContract.WeatherEntry.CONTENT_URI,
                    null,
                    null);

            /* Insert our new weather data into Sunshine's ContentProvider */
            sunshineContentResolver.bulkInsert(
                    WeatherContract.WeatherEntry.CONTENT_URI,
                    weatherValues);
        }

        /* If the code reaches this point, we have successfully performed our sync */

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }
}
 
开发者ID:fjoglar,项目名称:android-dev-challenge,代码行数:56,代码来源:SunshineSyncTask.java

示例9: handleMessage

import android.content.ContentResolver; //导入方法依赖的package包/类
@Override
public void handleMessage(Message msg) {
    final ContentResolver resolver = mResolver.get();
    if (resolver == null) return;

    WorkerArgs args = (WorkerArgs) msg.obj;

    int token = msg.what;
    int event = msg.arg1;

    switch (event) {
        case EVENT_ARG_QUERY:
            Cursor cursor;
            try {
                cursor = resolver.query(args.uri, args.projection,
                        args.selection, args.selectionArgs,
                        args.orderBy);
                // Calling getCount() causes the cursor window to be filled,
                // which will make the first access on the main thread a lot faster.
                if (cursor != null) {
                    cursor.getCount();
                }
            } catch (Exception e) {
                Log.w(TAG, "Exception thrown during handling EVENT_ARG_QUERY", e);
                cursor = null;
            }

            args.result = cursor;
            break;

        case EVENT_ARG_INSERT:
            args.result = resolver.insert(args.uri, args.values);
            break;

        case EVENT_ARG_BULK_INSERT:
            args.result = resolver.bulkInsert(args.uri, args.valuesArray);
            break;

        case EVENT_ARG_UPDATE:
            args.result = resolver.update(args.uri, args.values, args.selection,
                    args.selectionArgs);
            break;

        case EVENT_ARG_DELETE:
            args.result = resolver.delete(args.uri, args.selection, args.selectionArgs);
            break;
    }

    // passing the original token value back to the caller
    // on top of the event values in arg1.
    Message reply = args.handler.obtainMessage(token);
    reply.obj = args;
    reply.arg1 = msg.arg1;

    if (localLOGV) {
        Log.d(TAG, "WorkerHandler.handleMsg: msg.arg1=" + msg.arg1
                + ", reply.what=" + reply.what);
    }

    reply.sendToTarget();
}
 
开发者ID:Madrapps,项目名称:AsyncQuery,代码行数:62,代码来源:AsyncQueryHandler.java

示例10: handleSubtitles

import android.content.ContentResolver; //导入方法依赖的package包/类
private static int handleSubtitles(ContentResolver cr) {
    Uri uri = VideoStore.Files.getContentUri("external");
    String sortOrder = VideoStore.Video.VideoColumns.BUCKET_ID;
    // videos need name and id
    List<Pair<String, Long>> videos = new ArrayList<Pair<String, Long>>();
    // subtitles need id, name, size, language, ...
    List<SubtitleInfo> subs = new ArrayList<SubtitleInfo>();
    // inserts to do
    List<ContentValues> inserts = new ArrayList<ContentValues>();

    Cursor c = cr.query(uri, PROJ_ID_DATA_SIZE, SEL_VIDS_N_SUBS, null, sortOrder);
    if (c != null) {
        String lastBucket = null;
        while (c.moveToNext()) {
            long id = c.getLong(0);
            String file = c.getString(1);
            long size = c.getLong(2);
            String bucketId = c.getString(3);
            int mediaType = c.getInt(4);
            // if bucket switches, handle old bucket
            if (!bucketId.equals(lastBucket)) {
                handleSubtitleBucket(videos, subs, inserts);
                // update current bucket & empty lists
                lastBucket = bucketId;
                videos.clear();
                subs.clear();
            }
            // add videos & subtitles to their lists
            switch (mediaType) {
                case VideoStore.Files.FileColumns.MEDIA_TYPE_VIDEO:
                    videos.add(Pair.create(ArchosMediaFile.getFileTitle(file), Long.valueOf(id)));
                    break;
                case VideoStore.Files.FileColumns.MEDIA_TYPE_SUBTITLE:
                    subs.add(new SubtitleInfo(id, file, size));
                    break;
                default:
                    // should be impossible
                    Log.e(TAG, "Bad MediaType:" + mediaType + " when scanning videos and subtitles");
                    break;
            }

        }
        c.close();
    }
    // handle any remaining videos and subtitles
    handleSubtitleBucket(videos, subs, inserts);

    // insert new subtitle associations
    if (inserts.size() > 0) {
        ContentValues[] values = new ContentValues[inserts.size()];
        values = inserts.toArray(values);
        return cr.bulkInsert(SUBS_URI, values);
    }
    return 0;
}
 
开发者ID:archos-sa,项目名称:aos-MediaLib,代码行数:56,代码来源:NetworkScannerServiceVideo.java


注:本文中的android.content.ContentResolver.bulkInsert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。