Example usage for android.os Bundle putByteArray

List of usage examples for android.os Bundle putByteArray

Introduction

In this page you can find the example usage for android.os Bundle putByteArray.

Prototype

@Override
public void putByteArray(@Nullable String key, @Nullable byte[] value) 

Source Link

Document

Inserts a byte array value into the mapping of this Bundle, replacing any existing value for the given key.

Usage

From source file:com.nextgis.mobile.fragment.MapFragment.java

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(BUNDLE_KEY_IS_MEASURING, mRulerOverlay.isMeasuring());
    outState.putInt(KEY_MODE, mMode);/*w  w w.j av a2  s  .  c o  m*/
    outState.putInt(BUNDLE_KEY_LAYER, null == mSelectedLayer ? Constants.NOT_FOUND : mSelectedLayer.getId());

    Feature feature = mEditLayerOverlay.getSelectedFeature();
    outState.putLong(BUNDLE_KEY_FEATURE_ID, null == feature ? Constants.NOT_FOUND : feature.getId());

    if (null != feature && feature.getGeometry() != null) {
        try {
            outState.putByteArray(BUNDLE_KEY_SAVED_FEATURE, feature.getGeometry().toBlob());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.shurik.droidzebra.ZebraEngine.java

private JSONObject Callback(int msgcode, JSONObject data) {
    JSONObject retval = null;//  w  ww.j  ava  2  s  .  co  m
    Message msg = mHandler.obtainMessage(msgcode);
    Bundle b = new Bundle();
    msg.setData(b);
    // Log.d("ZebraEngine", String.format("Callback(%d,%s)", msgcode, data.toString()));
    if (bInCallback)
        fatalError("Recursive vallback call");
    try {
        bInCallback = true;
        switch (msgcode) {
        case MSG_ERROR: {
            b.putString("error", data.getString("error"));
            if (getEngineState() == ES_INITIAL) {
                // delete .bin files if initialization failed
                // will be recreated from resources
                new File(mFilesDir, PATTERNS_FILE).delete();
                new File(mFilesDir, BOOK_FILE).delete();
                new File(mFilesDir, BOOK_FILE_COMPRESSED).delete();
            }
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_DEBUG: {
            b.putString("message", data.getString("message"));
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_BOARD: {
            int len;
            JSONObject info;
            JSONArray zeArray;
            byte[] moves;

            JSONArray zeboard = data.getJSONArray("board");
            byte newBoard[] = new byte[BOARD_SIZE * BOARD_SIZE];
            for (int i = 0; i < zeboard.length(); i++) {
                JSONArray row = zeboard.getJSONArray(i);
                for (int j = 0; j < row.length(); j++) {
                    newBoard[i * BOARD_SIZE + j] = (byte) row.getInt(j);
                }
            }
            b.putByteArray("board", newBoard);
            b.putInt("side_to_move", data.getInt("side_to_move"));
            mCurrentGameState.mDisksPlayed = data.getInt("disks_played");

            // black info
            {
                Bundle black = new Bundle();
                info = data.getJSONObject("black");
                black.putString("time", info.getString("time"));
                black.putFloat("eval", (float) info.getDouble("eval"));
                black.putInt("disc_count", info.getInt("disc_count"));
                black.putString("time", info.getString("time"));

                zeArray = info.getJSONArray("moves");
                len = zeArray.length();
                moves = new byte[len];
                assert (2 * len <= mCurrentGameState.mMoveSequence.length);
                for (int i = 0; i < len; i++) {
                    moves[i] = (byte) zeArray.getInt(i);
                    mCurrentGameState.mMoveSequence[2 * i] = moves[i];
                }
                black.putByteArray("moves", moves);
                b.putBundle("black", black);
            }

            // white info
            {
                Bundle white = new Bundle();
                info = data.getJSONObject("white");
                white.putString("time", info.getString("time"));
                white.putFloat("eval", (float) info.getDouble("eval"));
                white.putInt("disc_count", info.getInt("disc_count"));
                white.putString("time", info.getString("time"));

                zeArray = info.getJSONArray("moves");
                len = zeArray.length();
                moves = new byte[len];
                assert ((2 * len + 1) <= mCurrentGameState.mMoveSequence.length);
                for (int i = 0; i < len; i++) {
                    moves[i] = (byte) zeArray.getInt(i);
                    mCurrentGameState.mMoveSequence[2 * i + 1] = moves[i];
                }
                white.putByteArray("moves", moves);
                b.putBundle("white", white);
            }

            mHandler.sendMessage(msg);
        }
            break;

        case MSG_CANDIDATE_MOVES: {
            JSONArray jscmoves = data.getJSONArray("moves");
            CandidateMove cmoves[] = new CandidateMove[jscmoves.length()];
            mValidMoves = new int[jscmoves.length()];
            for (int i = 0; i < jscmoves.length(); i++) {
                JSONObject jscmove = jscmoves.getJSONObject(i);
                mValidMoves[i] = jscmoves.getJSONObject(i).getInt("move");
                cmoves[i] = new CandidateMove(new Move(jscmove.getInt("move")));
            }
            msg.obj = cmoves;
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_GET_USER_INPUT: {
            mMovesWithoutInput = 0;

            setEngineState(ES_USER_INPUT_WAIT);

            waitForEngineState(ES_PLAY);

            while (mPendingEvent == null) {
                setEngineState(ES_USER_INPUT_WAIT);
                waitForEngineState(ES_PLAY);
            }

            retval = mPendingEvent;

            setEngineState(ES_PLAYINPROGRESS);

            mValidMoves = null;
            mPendingEvent = null;
        }
            break;

        case MSG_PASS: {
            setEngineState(ES_USER_INPUT_WAIT);
            mHandler.sendMessage(msg);
            waitForEngineState(ES_PLAY);
            setEngineState(ES_PLAYINPROGRESS);
        }
            break;

        case MSG_OPENING_NAME: {
            b.putString("opening", data.getString("opening"));
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_LAST_MOVE: {
            b.putInt("move", data.getInt("move"));
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_GAME_START: {
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_GAME_OVER: {
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_MOVE_START: {
            mMoveStartTime = android.os.SystemClock.uptimeMillis();

            mSideToMove = data.getInt("side_to_move");

            // can change player info here
            if (mPlayerInfoChanged) {
                zeSetPlayerInfo(PLAYER_BLACK, mPlayerInfo[PLAYER_BLACK].skill,
                        mPlayerInfo[PLAYER_BLACK].exactSolvingSkill, mPlayerInfo[PLAYER_BLACK].wldSolvingSkill,
                        mPlayerInfo[PLAYER_BLACK].playerTime, mPlayerInfo[PLAYER_BLACK].playerTimeIncrement);
                zeSetPlayerInfo(PLAYER_WHITE, mPlayerInfo[PLAYER_WHITE].skill,
                        mPlayerInfo[PLAYER_WHITE].exactSolvingSkill, mPlayerInfo[PLAYER_WHITE].wldSolvingSkill,
                        mPlayerInfo[PLAYER_WHITE].playerTime, mPlayerInfo[PLAYER_WHITE].playerTimeIncrement);
                zeSetPlayerInfo(PLAYER_ZEBRA, mPlayerInfo[PLAYER_ZEBRA].skill,
                        mPlayerInfo[PLAYER_ZEBRA].exactSolvingSkill, mPlayerInfo[PLAYER_ZEBRA].wldSolvingSkill,
                        mPlayerInfo[PLAYER_ZEBRA].playerTime, mPlayerInfo[PLAYER_ZEBRA].playerTimeIncrement);
            }
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_MOVE_END: {
            // introduce delay between moves made by the computer without user input
            // so we can actually to see that the game is being played :)
            if (mMoveDelay > 0 || (mMovesWithoutInput > 1 && mPlayerInfo[mSideToMove].skill > 0)) {
                long moveEnd = android.os.SystemClock.uptimeMillis();
                int delay = mMoveDelay > 0 ? mMoveDelay : SELFPLAY_MOVE_DELAY;
                if ((moveEnd - mMoveStartTime) < delay) {
                    android.os.SystemClock.sleep(delay - (moveEnd - mMoveStartTime));
                }
            }

            // this counter is reset by user input
            mMovesWithoutInput += 1;

            mHandler.sendMessage(msg);
        }
            break;

        case MSG_EVAL_TEXT: {
            b.putString("eval", data.getString("eval"));
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_PV: {
            JSONArray zeArray = data.getJSONArray("pv");
            int len = zeArray.length();
            byte[] moves = new byte[len];
            for (int i = 0; i < len; i++)
                moves[i] = (byte) zeArray.getInt(i);
            b.putByteArray("pv", moves);
            mHandler.sendMessage(msg);
        }
            break;

        case MSG_CANDIDATE_EVALS: {
            JSONArray jscevals = data.getJSONArray("evals");
            CandidateMove cmoves[] = new CandidateMove[jscevals.length()];
            for (int i = 0; i < jscevals.length(); i++) {
                JSONObject jsceval = jscevals.getJSONObject(i);
                cmoves[i] = new CandidateMove(new Move(jsceval.getInt("move")), jsceval.getString("eval_s"),
                        jsceval.getString("eval_l"), (jsceval.getInt("best") != 0));
            }
            msg.obj = cmoves;
            mHandler.sendMessage(msg);

        }
            break;

        default: {
            b.putString("error", String.format("Unkown message ID %d", msgcode));
            msg.setData(b);
            mHandler.sendMessage(msg);
        }
            break;
        }
    } catch (JSONException e) {
        msg.what = MSG_ERROR;
        b.putString("error", "JSONException:" + e.getMessage());
        msg.setData(b);
        mHandler.sendMessage(msg);
    } finally {
        bInCallback = false;
    }
    return retval;
}

From source file:com.easy.facebook.android.apicall.GraphApi.java

private String createEventsCall(long startTime, long endTime, String name, String urlPicture, String privacy,
        String description, String location, String street, String city, String state, String country,
        String latitude, String longitude, String zip) throws EasyFacebookError {

    String eventID = null;//from ww w  .java 2  s.  c  o  m

    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());
    params.putString("start_time", Long.toString(startTime).substring(0, 10));
    params.putString("end_time", Long.toString(endTime).substring(0, 10));
    params.putString("name", name);
    params.putString("description", description);
    params.putString("location", location);
    params.putString("street", street);
    params.putString("city", city);
    params.putString("state", state);
    params.putString("country", country);
    params.putString("latitude", latitude);
    params.putString("longitude", longitude);
    params.putString("zip", zip);
    params.putString("privacy", privacy);

    if (urlPicture != null) {
        String pictureName = urlPicture.substring(urlPicture.lastIndexOf('/'), urlPicture.length());
        params.putByteArray(pictureName, Util.loadPicture(urlPicture));
    }

    try {

        String jsonResponse = Util.openUrl("https://graph.facebook.com/me/events", "POST", params);

        JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse);

        if (!objectJSONErrorCheck.isNull("error")) {
            throw new EasyFacebookError(jsonResponse);

        }

        JSONObject json = new JSONObject(jsonResponse);

        if (json.has("id"))
            eventID = json.get("id").toString();

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return eventID;

}

From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java

public Thread videoUploadToFacebook(final Activity activity, final Handler handler, final Facebook mFacebook,
        final String path, final String title, final String description, final String emailAddress,
        final long sdrecord_id) {

    // Make the progress bar view visible.
    ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_FB);
    final Resources res = activity.getResources();

    Thread t = new Thread(new Runnable() {
        public void run() {
            // Do background task.
            // Track errors
            boolean failed = false;

            Log.i(TAG, "Upload starting");
            // Initialising REST API video.upload parameters
            Bundle params = new Bundle();

            params.putString("method", "facebook.video.upload");
            params.putString("format", "json");
            params.putString("title", title);
            params.putString("description", description);
            params.putString("call_id", String.valueOf(System.currentTimeMillis()));
            params.putString("v", "1.0");
            params.putString("oauth_token", mFacebook.getAccessToken());

            // Reading input file
            try {
                File videoFile = new File(path);
                byte[] data = null;
                try {

                    // XXX
                    // SPLIT THIS INTO 5K chunks!!
                    // XXX

                    data = new byte[(int) videoFile.length()];
                } catch (OutOfMemoryError e) {
                    failed = true;/*  w ww .  j  a  va2 s  .c  o  m*/
                }
                if (data != null) {
                    InputStream is = new FileInputStream(videoFile);
                    is.read(data);
                    params.putByteArray(videoFile.getName(), data);
                }
            } catch (Exception ex) {
                Log.e(TAG, "Cannot read video file :", ex);
            }

            // Sending POST request to Facebook
            String response = null;
            String url = "https://api-video.facebook.com/restserver.php";

            try {
                if (!failed) {
                    response = Util.openUrl(url, "POST", params);
                }
                // SessionEvents.onUploadComplete(response);
            } catch (FileNotFoundException e) {
                // SessionEvents.onFileNotFoundException(e);
                failed = true;
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // SessionEvents.onMalformedURLException(e);
                failed = true;
                e.printStackTrace();
            } catch (IOException e) {
                // SessionEvents.onIOException(e);
                failed = true;
                e.printStackTrace();
            } catch (OutOfMemoryError e) {
                failed = true;
                e.printStackTrace();
            }

            if (failed) {
                // Use the handler to execute a Runnable on the
                // main thread in order to have access to the
                // UI elements.

                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

                return;
            }

            Log.i(TAG, "Uploading to facebook complete. Response is " + response);

            // response is JSON
            JSONObject fb_response = null;
            // decode, and grab URL
            try {
                fb_response = (JSONObject) new JSONTokener(response).nextValue();
            } catch (JSONException e) {
                //
                e.printStackTrace();
                fb_response = null;
            }
            String hosted_url = "facebook.com";

            if (fb_response != null) {

                try {
                    hosted_url = fb_response.getString("link");
                    Log.i(TAG, "Facebook hosted url is : " + hosted_url);
                } catch (JSONException e) {
                    //
                    e.printStackTrace();
                    hosted_url = null;
                }

                if (hosted_url != null) {
                    // Log record of this URL in POSTs table
                    dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, url, hosted_url, "");

                    mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                    // Use the handler to execute a Runnable on the
                    // main thread in order to have access to the
                    // UI elements.
                    handler.postDelayed(new Runnable() {

                        public void run() {
                            // Update UI

                            // Indicate back to calling activity the result!
                            // update uploadInProgress state also.

                            ((VidiomActivity) activity).finishedUploading(true);
                            ((VidiomActivity) activity)
                                    .createNotification(res.getString(R.string.upload_to_facebook_succeeded_));

                        }
                    }, 0);
                }

            } else {

                // an error -- fb_response is NULL.
                mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_FB);

                handler.postDelayed(new Runnable() {
                    public void run() {
                        // Update UI

                        // Indicate back to calling activity the result!
                        // update uploadInProgress state also.

                        ((VidiomActivity) activity).finishedUploading(false);
                        ((VidiomActivity) activity)
                                .createNotification(res.getString(R.string.upload_to_facebook_failed_));
                    }
                }, 0);

            }

            if (emailAddress != null && fb_response != null && hosted_url != null) {

                // EmailSender through IR controlled gmail system.
                SSLEmailSender sender = new SSLEmailSender(
                        activity.getString(R.string.automatic_email_username),
                        activity.getString(R.string.automatic_email_password)); // consider
                // this
                // public
                // knowledge.
                try {
                    sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(),
                            activity.getString(R.string.url_of_hosted_video_is_) + " " + hosted_url, // body.getText().toString(),
                            activity.getString(R.string.automatic_email_from), // from.getText().toString(),
                            emailAddress // to.getText().toString()
                    );
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }

        }
    });

    t.start();

    return t;

}

From source file:org.mozilla.gecko.GeckoApp.java

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mOwnActivityDepth > 0)
        return; // we're showing one of our own activities and likely won't get paged out

    if (outState == null)
        outState = new Bundle();

    new SessionSnapshotRunnable(null).run();

    outState.putString(SAVED_STATE_TITLE, mLastTitle);
    outState.putString(SAVED_STATE_VIEWPORT, mLastViewport);
    outState.putByteArray(SAVED_STATE_SCREEN, mLastScreen);
    outState.putBoolean(SAVED_STATE_SESSION, true);
}

From source file:org.mdc.chess.MDChess.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (ctrl != null) {
        byte[] data = ctrl.toByteArray();
        outState.putByteArray("gameState", data);
        outState.putInt("gameStateVersion", 3);
    }/*from w  w w  .ja  v  a  2s .c o  m*/
}

From source file:tv.ouya.sdk.CordovaOuyaPlugin.java

public void initOuyaPlugin(final JSONArray jsonArray) {
    if (null == jsonArray) {
        JSONObject result = createError(0, "initOuyaPlugin jsonArray is null!");
        sCallbackInitOuyaPlugin.error(result);
        return;//from  w  w  w.j a  v a 2  s  . c o m
    }

    if (sEnableLogging) {
        Log.i(TAG, "initOuyaPlugin jsonArray=" + jsonArray.toString());
    }

    sInitCompletedListener = new CancelIgnoringOuyaResponseListener<Bundle>() {
        @Override
        public void onSuccess(final Bundle info) {
            if (sEnableLogging) {
                Log.i(TAG, "sInitCompletedListener: onSuccess");
            }
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS");
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            if (sEnableLogging) {
                Log.i(TAG, "sInitCompletedListener: onFailure errorCode=" + errorCode + " errorMessage="
                        + errorMessage);
            }
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR, result);
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }
    };

    sRequestGamerInfoListener = new CancelIgnoringOuyaResponseListener<GamerInfo>() {
        @Override
        public void onSuccess(final GamerInfo info) {
            Log.i(TAG, "sRequestGamerInfoListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("username", info.getUsername());
                        result.put("uuid", info.getUuid());
                    } catch (JSONException e) {
                        result = createError(0, "Failed to create results!");
                        sCallbackRequestGamerInfo.error(result);
                        return;
                    }
                    sCallbackRequestGamerInfo.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestGamerInfoListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestGamerInfo.error(result);
                }
            });
        }
    };

    sRequestProductsListener = new CancelIgnoringOuyaResponseListener<List<Product>>() {
        @Override
        public void onSuccess(final List<Product> products) {
            Log.i(TAG, "sRequestProductsListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONArray result = new JSONArray();
                    try {
                        int i = 0;
                        for (Product product : products) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("description", product.getDescription());
                            jsonObject.put("identifier", product.getIdentifier());
                            jsonObject.put("name", product.getName());
                            jsonObject.put("localPrice", product.getLocalPrice());
                            result.put(i, jsonObject);
                            ++i;
                        }
                    } catch (JSONException e) {
                        JSONObject error = createError(0, "Failed to create results!");
                        sCallbackRequestProducts.error(error);
                        return;
                    }
                    sCallbackRequestProducts.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestProductsListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestProducts.error(result);
                }
            });
        }
    };

    sRequestPurchaseListener = new OuyaResponseListener<PurchaseResult>() {

        @Override
        public void onSuccess(final PurchaseResult purchaseResult) {
            Log.i(TAG, "sRequestPurchaseListener: onSuccess");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = new JSONObject();
                    try {
                        result.put("productIdentifier", purchaseResult.getProductIdentifier());
                    } catch (JSONException e) {
                        result = createError(0, "Failed to set productIdentifier!");
                        sCallbackRequestPurchase.error(result);
                        return;
                    }
                    sCallbackRequestPurchase.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.i(TAG, "sRequestPurchaseListener: onFailure errorCode=" + errorCode + " errorMessage="
                    + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestPurchase.error(result);
                }
            });
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "sRequestPurchaseListener: onCancel");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Purchase was cancelled!");
                    sCallbackRequestPurchase.error(result);
                }
            });
        }
    };

    sRequestReceiptsListener = new OuyaResponseListener<Collection<Receipt>>() {

        @Override
        public void onSuccess(final Collection<Receipt> receipts) {
            Log.i(TAG, "requestReceipts onSuccess: received " + receipts.size() + " receipts");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONArray result = new JSONArray();
                    try {
                        int i = 0;
                        for (Receipt receipt : receipts) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("currency", receipt.getCurrency());
                            jsonObject.put("generatedDate", receipt.getGeneratedDate());
                            jsonObject.put("identifier", receipt.getIdentifier());
                            jsonObject.put("localPrice", receipt.getLocalPrice());
                            result.put(i, jsonObject);
                            ++i;
                        }
                    } catch (JSONException e) {
                        JSONObject error = createError(0, "Failed to create results!");
                        sCallbackRequestReceipts.error(error);
                        return;
                    }
                    sCallbackRequestReceipts.success(result);
                }
            });
        }

        @Override
        public void onFailure(final int errorCode, final String errorMessage, final Bundle optionalData) {
            Log.e(TAG, "requestReceipts onFailure: errorCode=" + errorCode + " errorMessage=" + errorMessage);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(errorCode, errorMessage);
                    sCallbackRequestReceipts.error(result);
                }
            });
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "requestReceipts onCancel");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Request Receipts was cancelled!");
                    sCallbackRequestReceipts.error(result);
                }
            });
        }
    };

    Runnable runnable = new Runnable() {
        public void run() {

            Bundle developerInfo = new Bundle();

            try {
                for (int index = 0; index < jsonArray.length(); ++index) {
                    JSONObject jsonObject = jsonArray.getJSONObject(index);
                    String name = jsonObject.getString("key");
                    String value = jsonObject.getString("value");
                    if (null == name || null == value) {
                        continue;
                    }
                    if (name.equals("tv.ouya.product_id_list")) {
                        String[] productIds = value.split(",");
                        if (null == productIds) {
                            continue;
                        }
                        developerInfo.putStringArray("tv.ouya.product_id_list", productIds);
                    } else {
                        Log.i(TAG, "initOuyaPlugin name=" + name + " value=" + value);
                        developerInfo.putString(name, value);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "initOuyaPlugin Failed to read JSON data!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });

                return;
            }

            byte[] applicationKey = null;

            // load the application key from assets
            try {
                AssetManager assetManager = cordova.getActivity().getAssets();
                InputStream inputStream = assetManager.open("key.der", AssetManager.ACCESS_BUFFER);
                applicationKey = new byte[inputStream.available()];
                inputStream.read(applicationKey);
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to load signing key!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });

                return;
            }

            if (null == applicationKey) {
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to load signing key!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            developerInfo.putByteArray(OuyaFacade.OUYA_DEVELOPER_PUBLIC_KEY, applicationKey);

            try {
                sOuyaFacade = OuyaFacade.getInstance();
            } catch (Exception e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to get OUYA Facade instance!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            /*
            try {
            sOuyaFacade.registerInitCompletedListener(sInitCompletedListener);
            } catch (Exception e) {
            e.printStackTrace();
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    JSONObject result = createError(0, "Failed to register init completed listener!");
                    sCallbackInitOuyaPlugin.error(result);
                }
            });
            return;
            }
            */

            try {
                sOuyaFacade.init(cordova.getActivity(), developerInfo);
            } catch (Exception e) {
                e.printStackTrace();
                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        JSONObject result = createError(0, "Failed to initialize the OuyaFacade!");
                        sCallbackInitOuyaPlugin.error(result);
                    }
                });
                return;
            }

            /*
            cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "WAIT");
                pluginResult.setKeepCallback(true);
                sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
            }
            });
            */

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "SUCCESS");
                    pluginResult.setKeepCallback(false);
                    sCallbackInitOuyaPlugin.sendPluginResult(pluginResult);
                }
            });
        }
    };
    cordova.getActivity().runOnUiThread(runnable);
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

private void showIntroductionInvite(String exchName, String introName, byte[] introPhoto, byte[] introPush,
        byte[] introPubKey, long msgRowId) {
    Bundle args = new Bundle();
    args.putString(extra.EXCH_NAME, exchName);
    args.putString(extra.INTRO_NAME, introName);
    args.putByteArray(extra.PHOTO, introPhoto);
    args.putByteArray(extra.PUSH_REGISTRATION_ID, introPush);
    args.putByteArray(extra.INTRO_PUBKEY, introPubKey);
    args.putLong(extra.MESSAGE_ROW_ID, msgRowId);
    if (!isFinishing()) {
        removeDialog(DIALOG_INTRO);/*from ww  w .  j a  va2 s  .c  om*/
        showDialog(DIALOG_INTRO, args);
    }
}

From source file:edu.cmu.cylab.starslinger.view.HomeActivity.java

protected void showChangeSenderOptions() {
    UseContactItem profile = getContactProfile();

    String name = SafeSlingerPrefs.getContactName();
    ArrayList<UseContactItem> contacts = getUseContactItemsByName(name);

    boolean isContactInUse = !TextUtils.isEmpty(SafeSlingerPrefs.getContactLookupKey());

    Bundle args = new Bundle();
    args.putBoolean(extra.CREATED, isContactInUse);
    if (profile != null) {
        args.putString(extra.NAME, profile.text);
        args.putByteArray(extra.PHOTO, profile.icon);
        args.putString(extra.CONTACT_LOOKUP_KEY, profile.contactLookupKey);
    }// w w  w. j a  v  a 2s .  c  om
    if (contacts != null) {
        for (int i = 0; i < contacts.size(); i++) {
            UseContactItem c = contacts.get(i);
            args.putString(extra.NAME + i, c.text);
            args.putByteArray(extra.PHOTO + i, c.icon);
            args.putString(extra.CONTACT_LOOKUP_KEY + i, c.contactLookupKey);
        }
    }
    if (!isFinishing()) {
        removeDialog(DIALOG_USEROPTIONS);
        showDialog(DIALOG_USEROPTIONS, args);
    }
}

From source file:com.if3games.chessonline.DroidFish.java

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (isSinglePlayer) {
        if (ctrl != null) {
            byte[] data = ctrl.toByteArray();
            outState.putByteArray("gameState", data);
            outState.putInt("gameStateVersion", 3);
        }//from  w w w.  ja v  a2  s .  c o  m
    }
}