Example usage for android.os Bundle getString

List of usage examples for android.os Bundle getString

Introduction

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

Prototype

@Nullable
public String getString(@Nullable String key) 

Source Link

Document

Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

Usage

From source file:com.scm.reader.livescanner.search.ImageRecognizer.java

public Search query(final Context context, Search dataToPopulate) throws IOException {

    String searchUrl = KConfig.getConfig().getServer();

    LogUtils.logDebug("qurl " + searchUrl);

    String apiKey = null;/*from  w  w  w.  j a v  a 2  s.co m*/
    String apiSecret = null;

    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        apiKey = bundle.getString(API_KEY_NAME);
        apiSecret = bundle.getString(API_SECRET_NAME);

    } catch (NameNotFoundException e) {
        Log.e(TAG, "Failed to load API_KEY or SECRET from meta-data, NameNotFound: " + e.getMessage());
        throw new RuntimeException("API_KEY or SECRET not found.");
    } catch (NullPointerException e) {
        Log.e(TAG, "Failed to load API_KEY or SECRET from meta-data, NullPointer: " + e.getMessage());
        throw new RuntimeException("API_KEY or SECRET not found.");
    }

    SearchRequestBuilder requestBuilderV4 = new SearchRequestBuilder(
            new SearchRequestData(dataToPopulate.getImage(), dataToPopulate.getLatitude(),
                    dataToPopulate.getLongitude(), searchUrl, getDeviceId(context)),
            getPackageInfo(context), apiKey, apiSecret);

    String response = "";

    try {

        Map<String, String> params = new HashMap<String, String>();
        params.put("location:", dataToPopulate.getLatitude() + ", " + dataToPopulate.getLongitude());
        response = requestBuilderV4.query();

    } catch (InvalidKeyException e1) {
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        LogUtils.logWarn("IO exception while sending HTTP request and parsing response", e);
        throw e;
    }

    // Print the response to console
    System.out.println("HTTP Status: " + requestBuilderV4.getResponseStatus());
    System.out.println("HTTP Response: " + requestBuilderV4.getResponseBody());

    Search result = null;
    try {
        result = parseJSON(context, response, dataToPopulate);

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

}

From source file:org.planetmono.dcuploader.SignOnRealName.java

public Runnable getMethodSignOn(final Application app, final Bundle b, final Handler resultHandler) {
    return new Runnable() {
        public void run() {
            Message m = resultHandler.obtainMessage();
            Bundle bm = m.getData();/*w w  w .  j a v a 2  s. c  om*/

            Log.d("dcuploader", "authenticating...");

            String encdata = b.getString("enc_data");
            String name = b.getString("name");
            String code1 = b.getString("code1");
            String code2 = b.getString("code2");

            HttpPost post = new HttpPost(AUTH_URL);
            List<NameValuePair> vlist = new ArrayList<NameValuePair>();
            vlist.add(new BasicNameValuePair("enc_data", encdata));
            vlist.add(new BasicNameValuePair("result_code", "1"));
            vlist.add(new BasicNameValuePair("contract_type", "S"));
            vlist.add(new BasicNameValuePair("au_chk", "F"));
            vlist.add(new BasicNameValuePair("name", name));
            vlist.add(new BasicNameValuePair("juminid1", code1));
            vlist.add(new BasicNameValuePair("juminid2", code2));
            try {
                post.setEntity(new UrlEncodedFormEntity(vlist));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            HttpResponse response = null;
            try {
                response = app.sendPostRequest(post);
            } catch (Exception e) {
                e.printStackTrace();

                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);
                return;
            }

            HttpEntity entity = response.getEntity();
            BufferedReader r;
            try {
                r = new BufferedReader(new InputStreamReader(entity.getContent(), "EUC-KR"));

                while (true) {
                    String line = r.readLine();
                    if (line == null)
                        break;

                    if (line.contains(" ??  ")) {
                        bm.putBoolean("result", false);
                        bm.putString("resultString", "?? ");
                        resultHandler.sendMessage(m);
                        return;
                    }
                }
            } catch (Exception e) {
                bm.putBoolean("result", false);
                bm.putString("resultString", " ");
                resultHandler.sendMessage(m);

                return;
            }

            /* abnormal status. traffic limit exceeded? */
            bm.putBoolean("result", true);
            resultHandler.sendMessage(m);
        }
    };
}

From source file:io.selendroid.ServerInstrumentation.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w  .  j  a  va 2s  .c  o m*/
public void onCreate(Bundle arguments) {

    String activityClazzName = arguments.getString("main_activity");

    int parsedServerPort = 0;

    try {
        String port = arguments.getString("server_port");
        if (port != null && port.isEmpty() == false) {
            parsedServerPort = Integer.parseInt(port);
        }
    } catch (NumberFormatException ex) {
        SelendroidLogger.log("Unable to parse the value of server_port key.");
        parsedServerPort = this.serverPort;
    }

    if (isValidPort(parsedServerPort)) {
        this.serverPort = parsedServerPort;
    }

    Class<? extends Activity> clazz = null;
    try {
        clazz = (Class<? extends Activity>) Class.forName(activityClazzName);
    } catch (ClassNotFoundException exception) {
        SelendroidLogger.log("The class with name '" + activityClazzName + "' does not exist.", exception);
    }
    mainActivity = clazz;
    SelendroidLogger.log("Instrumentation initialized with main activity: " + activityClazzName);
    if (clazz == null) {
        SelendroidLogger.log("Clazz is null - but should be an instance of: " + activityClazzName);
    }
    instance = this;

    mainThreadExecutor = provideMainThreadExecutor(Looper.getMainLooper());
    uiController = new UiThreadController();

    start();
}

From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java

protected void Prepare(GetFiresService c) {
    this.c = c;/*from  www. j a v a 2 s  .  c  om*/
    nID = -1;
    bHasNews = false;

    mFillDataHandler = new Handler() {
        public void handleMessage(Message msg) {

            Bundle resultData = msg.getData();
            boolean bHaveErr = resultData.getBoolean(GetFiresService.ERROR);
            if (bHaveErr) {
                SendError(resultData.getString(GetFiresService.ERR_MSG));
            } else {
                int nType = resultData.getInt(GetFiresService.SOURCE);
                String sData = resultData.getString(GetFiresService.JSON);
                switch (nType) {
                case 5:
                    FillData(nType, sData);
                    break;
                default:
                    break;
                }
            }
        };
    };

    mmoItems = new HashMap<Long, ScanexNotificationItem>();
}

From source file:com.example.ridemepassenger.WaitHeComeActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SDKInitializer.initialize(getApplicationContext());
    setContentView(R.layout.activity_wait_he_come);

    Bundle extras = getIntent().getExtras();
    d_name = extras.getString(DRIVERNAME);
    d_phone = extras.getString(DRIVERPHONE);
    d_avatar = extras.getString(DRIVEAVATAR);
    d_license = extras.getString(DRIVERLICENSE);
    d_model = extras.getString(DRIVERMODEL);
    d_stars = extras.getString(DRIVERSTARS);
    d_dealnum = extras.getString(DRIVERDEALNUM);

    name_txt = (TextView) findViewById(R.id.wait_he_come_name);
    license_txt = (TextView) findViewById(R.id.wait_he_come_license);
    model_txt = (TextView) findViewById(R.id.wait_he_come_model);
    dealnum_txt = (TextView) findViewById(R.id.wait_he_come_tradenum);
    avatar = (ImageView) findViewById(R.id.show_order_avatar);
    dial = (ImageView) findViewById(R.id.wait_he_come_dial);
    commit_btn = (Button) findViewById(R.id.wait_he_come_bt);

    name_txt.setText(d_name);/*from  w  w  w .jav  a  2 s .co  m*/
    license_txt.setText(d_license);
    model_txt.setText(d_license);
    dealnum_txt.setText(d_dealnum);

    new GetImageCache(avatar, GetImageCache.PIC_NAME).execute(d_avatar);

    commit_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new sendto_sever().execute();
        }
    });

    dial.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            intent.setAction("android.intent.action.CALL");
            intent.setData(Uri.parse("tel:" + d_phone));//mobile
            startActivity(intent);
        }
    });

    mMapView = (MapView) findViewById(R.id.bmapView);
    mMapView.showScaleControl(false);
    mMapView.showZoomControls(false);
    mBaiduMap = mMapView.getMap();
    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(19f));
    //  
    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
    mLocationClient = new LocationClient(getApplicationContext()); //LocationClient
    initLocation();
    mLocationClient.registerLocationListener(myListener); //
    mLocationClient.start();
}

From source file:com.frublin.androidoauth2.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 ww.ja  v a2  s  . co m*/
 * @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;

    url = url + "?" + encodeUrl(params);

    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("oauth_token")) {
            String decoded_token = URLDecoder.decode(params.getString("oauth_token"));
            params.putString("oauth_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());
    }
    return response;
}

From source file:mp.paschalis.LentBookActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    app = (App) getApplication();/*from   w ww.ja  v a  2  s  .co m*/

    setContentView(R.layout.activity_lent_book);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Get arguments (User,Destination,ISBN)
    final Bundle extras = getIntent().getExtras();

    try {
        final String isbn = extras.getString(App.ExtrasForLentBookActivityISBN);

        fromEditBookActivity = true;

        gotISBN = isbn;

    } catch (Exception e) {
        Toast.makeText(LentBookActivity.this, "Something went wrong. Please report this", Toast.LENGTH_LONG)
                .show();
        fromEditBookActivity = false;
        LentBookActivity.this.finish();

    }

    progressBarLentButton = (ProgressBar) findViewById(R.id.progressBarLentButton);

    buttonLentBook = (Button) findViewById(R.id.buttonLentBook);

    editTextDestinationUsername = (EditText) findViewById(R.id.editTextDestinationUser);

    textViewLentResult = (TextView) findViewById(R.id.textViewLentResult);

    editTextDestinationUsername.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editTextDestinationUsername.getText().length() >= 4) {
                buttonLentBook.setEnabled(true);
            } else {
                buttonLentBook.setEnabled(false);
            }
        }
    });

    buttonLentBook.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            DataClassLentABook data = new DataClassLentABook();

            data.destinationUser = editTextDestinationUsername.getText().toString();

            data.isbn = gotISBN;

            new AsyncTaskLentABook().execute(data);

        }
    });

}

From source file:com.thanu.schoolbustracker.RouteActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_route);

    Intent intent = getIntent();//w w w  .  j a  v a 2s  . c om
    Bundle bundle = intent.getExtras();
    name = bundle.getString("uname");

    FragmentManager myFragmentManager = getFragmentManager();
    MapFragment myMapFragment = (MapFragment) myFragmentManager.findFragmentById(R.id.map);
    modifyRoute = (Button) findViewById(R.id.btnModifyRoute);

    myMap = myMapFragment.getMap();

    if (myMap != null) {

        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        myMap.getUiSettings().setCompassEnabled(false);
        myMap.getUiSettings().setRotateGesturesEnabled(true);
        myMap.getUiSettings().setScrollGesturesEnabled(true);
        myMap.getUiSettings().setZoomControlsEnabled(true);
        myMap.getUiSettings().setZoomGesturesEnabled(true);
        LatLng location = new LatLng(6.796923, 79.922433);
        CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(6.796923, 79.922433));
        myMap.moveCamera(center);
        CameraPosition cameraPosition = new CameraPosition.Builder().target(location) // Sets the center of the map to Mountain
                // View
                .zoom(10) // Sets the zoom
                .bearing((float) 112.5) // Sets the orientation of the
                // camera to east
                .tilt(30) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder
        myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        // Opening the sharedPreferences object
        sharedPreferences = getSharedPreferences("location", 0);

        // Getting number of locations already stored
        locationCount = sharedPreferences.getInt("locationCount", 0);

        // Getting stored zoom level if exists else return 0
        String zoom = sharedPreferences.getString("zoom", "0");

        // If locations are already saved
        if (locationCount != 0) {

            String lat = "";
            String lng = "";

            // Iterating through all the locations stored
            for (int i = 0; i < locationCount; i++) {

                // Getting the latitude of the i-th location
                lat = sharedPreferences.getString("lat" + i, "0");

                // Getting the longitude of the i-th location
                lng = sharedPreferences.getString("lng" + i, "0");

                // Drawing marker on the map
                drawMarker(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)));
            }

            // Moving CameraPosition to last clicked position
            myMap.moveCamera(CameraUpdateFactory
                    .newLatLng(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng))));

            // Setting the zoom level in the map on last position is clicked
            myMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(zoom)));
        }

        modifyRoute.setOnClickListener(this);
        myMap.setOnMapClickListener(this);
        myMap.setOnMapLongClickListener(this);
        myMap.setOnMarkerClickListener(this);
    }

    markerClicked = false;

    if (name.equalsIgnoreCase("Admin")) {
        modifyRoute.setEnabled(true);
    }
}

From source file:com.agiro.scanner.android.AppEngineClient.java

private String getAuthToken(Context context, Account account) {
    String authToken = null;//  www  .  ja v  a2 s .  c  o  m
    AccountManager accountManager = AccountManager.get(context);
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, false, null,
                null);
        Bundle bundle = future.getResult();
        Account[] accs = accountManager.getAccounts();
        Log.v(TAG, "Account size = " + accs.length);
        Log.v(TAG, "Listing accounts");
        for (Account acc : accs) {
            Log.v(TAG, "Account: " + acc);
        }
        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        // User will be asked for "App Engine" permission.
        if (authToken == null) {
            Log.e(TAG, "No authToken");
            // No auth token - will need to ask permission from user.
            Intent intent = new Intent("com.google.ctp.AUTH_PERMISSION");
            intent.putExtra("AccountManagerBundle", bundle);
            context.sendBroadcast(intent);
        }
    } catch (OperationCanceledException e) {
        Log.w(TAG, e.getMessage());
    } catch (AuthenticatorException e) {
        Log.w(TAG, e.getMessage());
    } catch (IOException e) {
        Log.w(TAG, e.getMessage());
    }
    return authToken;
}

From source file:com.arctech.gcm.MyGcmListenerService.java

/**
 * Called when message is received./*from   ww  w  . j  a v  a  2s.  c  o  m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);

    String message = data.getString("message");
    recipientStkid = data.getString("recipientStkid");
    stkidCheck = sharedPreferences.getString("stkid", "");
    chatRecipient = data.getString("chatRecipient");
    chatRecipientUrl = data.getString("chatRecipientUrl");
    senderToken = data.getString("senderToken");
    recipientToken = data.getString("recipientToken");
    ChattingActivity.firstConnect = true;
    Log.i(TAG, "recipient url : " + chatRecipientUrl);
    Log.i(TAG, "Message: " + message);
    this.message = message;
    Log.i(TAG, "msg " + message);
    sharedPreferences.edit().putString("message", message).apply();
    sharedPreferences.edit().putString("chatRecipientUrl", chatRecipientUrl).apply();
    sharedPreferences.edit().putString("recipientStkid", recipientStkid).apply();
    sharedPreferences.edit().putString("chatRecipientName", chatRecipient).apply();
    sharedPreferences.edit().putString("stkidCheck", stkidCheck).apply();
    sharedPreferences.edit().putString("senderToken", senderToken).apply();
    // sharedPreferences.edit().putString("recipientToken", recipientToken).apply();

    // Notify UI that registration has completed, so the progress indicator can be hidden.
    /*Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);*/
    //sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();

    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    if (!checkApp()) {
        sendNotification(message);
    }
}