List of usage examples for android.os Bundle getByteArray
@Override @Nullable public byte[] getByteArray(@Nullable String key)
From source file:com.facebook.android.Util.java
/** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String/*from w w w .j ava2 s . c o m*/ * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated public static String openUrl(String url, String method, Bundle params) throws IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Utility.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[]) parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); try { os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } finally { os.close(); } } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.evandroid.musica.fragment.LyricsViewFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setRetainInstance(true);//from w w w.ja va 2 s . c o m setHasOptionsMenu(true); View layout = inflater.inflate(R.layout.lyrics_view, container, false); if (savedInstanceState != null) try { Lyrics l = Lyrics.fromBytes(savedInstanceState.getByteArray("lyrics")); if (l != null) this.mLyrics = l; mSearchQuery = savedInstanceState.getString("searchQuery"); mSearchFocused = savedInstanceState.getBoolean("searchFocused"); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } else { Bundle args = getArguments(); if (args != null) try { Lyrics lyrics = Lyrics.fromBytes(args.getByteArray("lyrics")); this.mLyrics = lyrics; if (lyrics != null && lyrics.getText() == null && lyrics.getArtist() != null) { String artist = lyrics.getArtist(); String track = lyrics.getTrack(); String url = lyrics.getURL(); fetchLyrics(artist, track, url); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } if (layout != null) { Bundle args = savedInstanceState != null ? savedInstanceState : getArguments(); boolean screenOn = PreferenceManager.getDefaultSharedPreferences(getActivity()) .getBoolean("pref_force_screen_on", false); TextSwitcher textSwitcher = (TextSwitcher) layout.findViewById(R.id.switcher); textSwitcher.setFactory(new LyricsTextFactory(layout.getContext())); ActionMode.Callback callback = new CustomSelectionCallback(getActivity()); ((TextView) textSwitcher.getChildAt(0)).setCustomSelectionActionModeCallback(callback); ((TextView) textSwitcher.getChildAt(1)).setCustomSelectionActionModeCallback(callback); textSwitcher.setKeepScreenOn(screenOn); layout.findViewById(R.id.lrc_view).setKeepScreenOn(screenOn); TextView id3TV = (TextView) layout.findViewById(R.id.id3_tv); SpannableString text = new SpannableString(id3TV.getText()); text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0); id3TV.setText(text); final RefreshIcon refreshFab = (RefreshIcon) getActivity().findViewById(R.id.refresh_fab); refreshFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mRefreshLayout.isRefreshing()) fetchCurrentLyrics(true); } }); FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent settingsIntent = new Intent(getActivity(), SettingsActivity.class); startActivity(settingsIntent); } }); if (args != null) refreshFab.setEnabled(args.getBoolean("refreshFabEnabled", true)); mScrollView = (NestedScrollView) layout.findViewById(R.id.scrollview); mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); TypedValue primaryColor = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.colorPrimary, primaryColor, true); mRefreshLayout.setColorSchemeResources(primaryColor.resourceId, R.color.accent); float offset = getResources().getDisplayMetrics().density * 64; mRefreshLayout.setProgressViewEndTarget(true, (int) offset); mRefreshLayout.setOnRefreshListener(this); if (mLyrics == null) { if (!startEmtpy) fetchCurrentLyrics(false); } else if (mLyrics.getFlag() == Lyrics.SEARCH_ITEM) { mRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.refresh_layout); startRefreshAnimation(); if (mLyrics.getArtist() != null) fetchLyrics(mLyrics.getArtist(), mLyrics.getTrack()); } else //Rotation, resume update(mLyrics, layout, false); } if (broadcastReceiver == null) broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { searchResultLock = false; String artist = intent.getStringExtra("artist"); String track = intent.getStringExtra("track"); if (artist != null && track != null && mRefreshLayout.isEnabled()) { startRefreshAnimation(); new ParseTask(LyricsViewFragment.this, false, true).execute(mLyrics); } } }; return layout; }
From source file:com.concavenp.artistrymuse.fragments.SearchResultFragment.java
/** * Restore the instance data saved. This includes the User entered search string. * * @param savedInstanceState - The bundle of instance data saved *///from w ww . j av a 2 s . co m @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { mFlipper.setDisplayedChild( savedInstanceState.getInt(FLIP_ACTIVE_SEARCH_STRING + getDatabaseNameFromType(), 0)); try { switch (mType) { case USERS: { ByteArrayInputStream bais = new ByteArrayInputStream( savedInstanceState.getByteArray(SEARCH_STRING + getDatabaseNameFromType())); ObjectInputStream ois = new ObjectInputStream(bais); List<UserResponseHit> list = (List<UserResponseHit>) ois.readObject(); mUsersAdapter.clearData(); mUsersAdapter.add(list); break; } case PROJECTS: { ByteArrayInputStream bais = new ByteArrayInputStream( savedInstanceState.getByteArray(SEARCH_STRING + getDatabaseNameFromType())); ObjectInputStream ois = new ObjectInputStream(bais); List<ProjectResponseHit> list = (List<ProjectResponseHit>) ois.readObject(); mProjectsAdapter.clearData(); mProjectsAdapter.add(list); break; } } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
From source file:com.sentaroh.android.TextFileBrowser.MainActivity.java
private void restoreViewContents(Bundle savedState) { mSavedViewedFileListSpinnerPosition = savedState.getInt("SpinnerPos"); byte[] buf = savedState.getByteArray("FAH_List"); int list_size = savedState.getInt("FAH_Size"); try {/* w ww . j ava2 s . co m*/ ByteArrayInputStream bis = new ByteArrayInputStream(buf); ObjectInputStream ois = new ObjectInputStream(bis); mGlblParms.viewedFileList = new ArrayList<ViewedFileListItem>(); for (int i = 0; i < list_size; i++) { ViewedFileListItem vfli = new ViewedFileListItem(); vfli.readExternal(ois); mGlblParms.viewedFileList.add(vfli); } ois.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
From source file:de.persoapp.android.activity.AuthenticateActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.frame_layout); // we need this empty frame, otherwise Crouton may render its croutons wrong // default value setResult(RESULT_CANCELED);/*from w ww . j a va 2 s.c o m*/ Uri uri = getIntent().getData(); mTcUrl = uri != null ? uri.getQueryParameter(TC_TOKEN_PARAMETER) : null; if (mTcUrl == null) { // skip whole life cycle Toast.makeText(this, R.string.invalid_request, Toast.LENGTH_LONG).show(); finish(); return; } if (savedInstanceState == null) { if (!mDeviceStateTester.needsToShowOtherContent(R.id.frameLayout)) { startAuthentication(); } } else { mPin = savedInstanceState.getByteArray(PIN_KEY); mResultChat = savedInstanceState.getLong(RESULT_CHAT_KEY); } }
From source file:org.jboss.aerogear.android.impl.pipeline.SupportLoaderAdapter.java
@Override public Loader<T> onCreateLoader(int id, Bundle bundle) { this.idsForNamedPipes.put(name, id); Methods method = (Methods) bundle.get(METHOD); Callback callback = (Callback) bundle.get(CALLBACK); Loader loader = null;//w ww. ja va2s .c o m switch (method) { case READ: { ReadFilter filter = (ReadFilter) bundle.get(FILTER); loader = new SupportReadLoader(applicationContext, callback, pipe.getHandler(), filter, this); } break; case REMOVE: { String toRemove = Objects.firstNonNull(bundle.getString(REMOVE_ID), "-1"); loader = new SupportRemoveLoader(applicationContext, callback, pipe.getHandler(), toRemove); } break; case SAVE: { byte[] json = bundle.getByteArray(ITEM); T item = responseParser.handleResponse(new String(json), pipe.getKlass()); loader = new SupportSaveLoader(applicationContext, callback, pipe.getHandler(), item); } break; } return loader; }
From source file:com.razerzone.store.sdk.engine.gamemaker.Plugin.java
public static String init(final String secretApiKey) { if (sEnableLogging) { Log.d(TAG, "init: secretApiKey=" + secretApiKey); }/* w w w . jav a 2s .co m*/ final Activity activity = Plugin.getRelay().getCurrentActivity(); if (null == activity) { Log.d(TAG, "Current activity is null"); return sFalse; } else { Log.d(TAG, "Current activity is valid"); } final FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content); if (null == content) { Log.d(TAG, "Content is null"); return sFalse; } else { Runnable runnable = new Runnable() { public void run() { Log.d(TAG, "Disable screensaver"); content.setKeepScreenOn(true); Log.d(TAG, "Add inputView"); sInputView = new InputView(activity); Bundle developerInfo = null; try { developerInfo = StoreFacade.createInitBundle(secretApiKey); } catch (InvalidParameterException e) { Log.e(TAG, e.getMessage()); activity.finish(); return; } if (sEnableLogging) { Log.d(TAG, "developer_id=" + developerInfo.getString(StoreFacade.DEVELOPER_ID)); } if (sEnableLogging) { Log.d(TAG, "developer_public_key length=" + developerInfo.getByteArray(StoreFacade.DEVELOPER_PUBLIC_KEY).length); } sInitCompleteListener = new CancelIgnoringResponseListener<Bundle>() { @Override public void onSuccess(Bundle bundle) { if (sEnableLogging) { Log.d(TAG, "InitCompleteListener: onSuccess"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessInit"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); sInitialized = true; } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.d(TAG, "InitCompleteListener: onFailure errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureInit"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sStoreFacade = StoreFacade.getInstance(); try { sStoreFacade.init(activity, developerInfo, sInitCompleteListener); } catch (Exception e) { e.printStackTrace(); } sRequestLoginListener = new ResponseListener<Void>() { @Override public void onSuccess(Void result) { if (sEnableLogging) { Log.d(TAG, "sRequestLoginListener: onSuccess"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessRequestLogin"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.e(TAG, "sRequestLoginListener: onFailure errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureRequestLogin"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onCancel() { if (sEnableLogging) { Log.d(TAG, "sRequestLoginListener: onCancel"); } JSONObject json = new JSONObject(); try { json.put("method", "onCancelRequestLogin"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sRequestGamerInfoListener = new ResponseListener<GamerInfo>() { @Override public void onSuccess(GamerInfo info) { if (null == info) { Log.e(TAG, "GamerInfo is null!"); return; } if (sEnableLogging) { Log.d(TAG, "sRequestGamerInfoListener: onSuccess uuid=" + info.getUuid() + " username=" + info.getUsername()); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessRequestGamerInfo"); JSONObject data = new JSONObject(); data.put("uuid", info.getUuid()); data.put("username", info.getUsername()); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.e(TAG, "sRequestGamerInfoListener: onFailure errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureRequestGamerInfo"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onCancel() { if (sEnableLogging) { Log.d(TAG, "sRequestGamerInfoListener: onCancel"); } JSONObject json = new JSONObject(); try { json.put("method", "onCancelRequestGamerInfo"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sRequestProductsListener = new ResponseListener<List<Product>>() { @Override public void onSuccess(final List<Product> products) { if (null == products) { Log.e(TAG, "Products are null!"); return; } if (sEnableLogging) { Log.i(TAG, "sRequestProductsListener: onSuccess"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessRequestProducts"); JSONArray data = new JSONArray(); int index = 0; for (Product product : products) { JSONObject item = new JSONObject(); try { item.put("currencyCode", product.getCurrencyCode()); item.put("description", product.getDescription()); item.put("identifier", product.getIdentifier()); item.put("localPrice", product.getLocalPrice()); item.put("name", product.getName()); item.put("originalPrice", product.getOriginalPrice()); item.put("percentOff", product.getPercentOff()); item.put("developerName", product.getDeveloperName()); data.put(index, item); ++index; } catch (JSONException e2) { } } json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.e(TAG, "sRequestProductsListener: onFailure errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureRequestProducts"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onCancel() { if (sEnableLogging) { Log.i(TAG, "sRequestProductsListener: onCancel"); } JSONObject json = new JSONObject(); try { json.put("method", "onCancelRequestProducts"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sRequestPurchaseListener = new ResponseListener<PurchaseResult>() { @Override public void onSuccess(PurchaseResult result) { if (null == result) { Log.e(TAG, "PurchaseResult is null!"); return; } if (sEnableLogging) { Log.i(TAG, "sRequestPurchaseListener: onSuccess"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessRequestPurchase"); JSONObject data = new JSONObject(); data.put("identifier", result.getProductIdentifier()); data.put("ownerId", result.getOrderId()); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.e(TAG, "sRequestPurchaseListener: onFailure errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureRequestPurchase"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onCancel() { if (sEnableLogging) { Log.i(TAG, "sRequestPurchaseListener: onCancel"); } JSONObject json = new JSONObject(); try { json.put("method", "onCancelRequestPurchase"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sRequestReceiptsListener = new ResponseListener<Collection<Receipt>>() { @Override public void onSuccess(Collection<Receipt> receipts) { if (null == receipts) { Log.e(TAG, "Receipts are null!"); return; } if (sEnableLogging) { Log.i(TAG, "requestReceipts onSuccess: received " + receipts.size() + " receipts"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessRequestReceipts"); JSONArray data = new JSONArray(); int index = 0; for (Receipt receipt : receipts) { JSONObject item = new JSONObject(); try { item.put("identifier", receipt.getIdentifier()); item.put("purchaseDate", receipt.getPurchaseDate()); item.put("gamer", receipt.getGamer()); item.put("uuid", receipt.getUuid()); item.put("localPrice", receipt.getLocalPrice()); item.put("currency", receipt.getCurrency()); item.put("generatedDate", receipt.getGeneratedDate()); data.put(index, item); ++index; } catch (JSONException e2) { } } json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int errorCode, String errorMessage, Bundle optionalData) { if (sEnableLogging) { Log.e(TAG, "requestReceipts onFailure: errorCode=" + errorCode + " errorMessage=" + errorMessage); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureRequestReceipts"); JSONObject data = new JSONObject(); data.put("errorCode", Integer.toString(errorCode)); data.put("errorMessage", errorMessage); json.put("data", data); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onCancel() { if (sEnableLogging) { Log.i(TAG, "requestReceipts onCancel"); } JSONObject json = new JSONObject(); try { json.put("method", "onCancelRequestReceipts"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; sShutdownListener = new CancelIgnoringResponseListener<Void>() { @Override public void onSuccess(Void aVoid) { if (sEnableLogging) { Log.i(TAG, "shutdown onSuccess"); } JSONObject json = new JSONObject(); try { json.put("method", "onSuccessShutdown"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } @Override public void onFailure(int i, String s, Bundle bundle) { if (sEnableLogging) { Log.i(TAG, "shutdown onFailure"); } JSONObject json = new JSONObject(); try { json.put("method", "onFailureShutdown"); } catch (JSONException e1) { } String jsonData = json.toString(); sAsyncResults.add(jsonData); } }; Controller.init(activity); } }; activity.runOnUiThread(runnable); } return sTrue; }
From source file:com.charabia.SmsViewActivity.java
@Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mode = savedInstanceState.getInt("mode"); prefPhoneNumber = savedInstanceState.getString("prefPhoneNumber"); keypair = (KeyPair) savedInstanceState.getSerializable("keypair"); key = savedInstanceState.getByteArray("key"); phoneNumber = savedInstanceState.getString("phoneNumber"); }
From source file:com.wareninja.android.opensource.oauth2login.common.Utils.java
/** * Connect to an HTTP URL and return the response as a string. * /* w w w.j av a2 s . co m*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { /* if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } */ // YG: added this to avoid fups byte[] byteArr = null; try { byteArr = (byte[]) params.get(key); } catch (Exception ex1) { } if (byteArr != null) dataparams.putByteArray(key, byteArr); } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } if (AppContext.DEBUG) Log.d("Facebook-Util", method + " response: " + response); return response; }
From source file:com.facebook.Session.java
/** * Restores the saved session from a Bundle, if any. Returns the restored Session or * null if it could not be restored. This method is intended to be called from an Activity or Fragment's * onCreate method when a Session has previously been saved into a Bundle via saveState to preserve a Session * across Activity lifecycle events./*from w w w. j av a 2s.c o m*/ * * @param context the Activity or Service creating the Session, must not be null * @param cachingStrategy the TokenCachingStrategy to use to load and store the token. If this is * null, a default token cachingStrategy that stores data in * SharedPreferences will be used * @param callback the callback to notify for Session state changes, can be null * @param bundle the bundle to restore the Session from * @return the restored Session, or null */ public static final Session restoreSession(Context context, TokenCachingStrategy cachingStrategy, StatusCallback callback, Bundle bundle) { if (bundle == null) { return null; } byte[] data = bundle.getByteArray(SESSION_BUNDLE_SAVE_KEY); if (data != null) { ByteArrayInputStream is = new ByteArrayInputStream(data); try { Session session = (Session) (new ObjectInputStream(is)).readObject(); initializeStaticContext(context); if (cachingStrategy != null) { session.tokenCachingStrategy = cachingStrategy; } else { session.tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(context); } if (callback != null) { session.addCallback(callback); } session.authorizationBundle = bundle.getBundle(AUTH_BUNDLE_SAVE_KEY); return session; } catch (ClassNotFoundException e) { Log.w(TAG, "Unable to restore session", e); } catch (IOException e) { Log.w(TAG, "Unable to restore session.", e); } } return null; }