Example usage for android.content Intent getBooleanExtra

List of usage examples for android.content Intent getBooleanExtra

Introduction

In this page you can find the example usage for android.content Intent getBooleanExtra.

Prototype

public boolean getBooleanExtra(String name, boolean defaultValue) 

Source Link

Document

Retrieve extended data from the intent.

Usage

From source file:com.fbartnitzek.tasteemall.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v(LOG_TAG, "onActivityResult, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode
            + "], resultCode = [" + resultCode + "], data = [" + data + "]");

    if (requestCode == REQUEST_EXPORT_DIR_CODE
            || requestCode == REQUEST_IMPORT_FILES_CODE && resultCode == AppCompatActivity.RESULT_OK) {
        Uri uri;/*www  .ja  v  a2  s  .c  om*/
        if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {

            List<File> files = new ArrayList<>();
            // For JellyBean and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                ClipData clip = data.getClipData();

                if (clip != null) {
                    for (int i = 0; i < clip.getItemCount(); i++) {
                        uri = clip.getItemAt(i).getUri();
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                        // Do something with the URI
                    }
                }
                // For Ice Cream Sandwich
            } else {
                ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);

                if (paths != null) {
                    for (String path : paths) {
                        uri = Uri.parse(path); // TODO: might be useless conversion...
                        //                            Log.v(LOG_TAG, "onActivityResult, uri=" + uri + ", hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
                        files.add(new File(uri.getPath()));
                    }
                }
            }

            if (!files.isEmpty() && requestCode == REQUEST_IMPORT_FILES_CODE) {

                // TODO: refactor afterwards without mFiles
                // new ImportFilesTask(MPA.this, MPA.this).execute(files.toArray(new File[files.size()]));

                mFiles = files;
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("which import shall be used?")
                        .setPositiveButton("class-based", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new ImportFilesTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.toArray(new File[mFiles.size()]));
                                mFiles = null;
                            }
                        })
                        //                            .setNegativeButton("old", new DialogInterface.OnClickListener() {
                        //                                @Override
                        //                                public void onClick(DialogInterface dialog, int which) {
                        //                                    new ImportFilesOldFormatTask(MainActivity.this, MainActivity.this)
                        //                                            .execute(mFiles.toArray(new File[mFiles.size()]));
                        //                                    mFiles = null;
                        //                                }
                        //                            });
                        .setNegativeButton("all-in-1", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                // multiple all-in-1-files?
                                new ImportAllInOneFileTask(MainActivity.this, MainActivity.this)
                                        .execute(mFiles.get(0));
                                mFiles = null;
                                // to get all easier:
                                // either all ids are known or lots of parallel stuff...
                                // dialog with warning!
                                // task won't help => needs Dialog everywhere... => Task
                                // merge is to complicated for now :-p

                            }
                        });
                builder.show();
            }

        } else {
            //                Log.v(LOG_TAG, "onActivityResult - single file, hashCode=" + this.hashCode() + ", " + "requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
            uri = data.getData();
            // Do something with the URI
            if (uri != null && requestCode == REQUEST_EXPORT_DIR_CODE) {
                //somehow it returned a filepath (confusing use of multiple flag...
                new ExportToDirTask(this, this).execute(new File(uri.getPath()));
            }

        }

    } else if (requestCode == REQUEST_EDIT_PRODUCER_GEOCODE && resultCode == AppCompatActivity.RESULT_OK) {

        if (mProducerLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mProducerLocationUris == null! - should never happen...");
            return;
        }

        if (mProducerLocationUris.isEmpty()) {
            if (mReviewLocationUris != null && !mReviewLocationUris.isEmpty()) {
                showReviewLocationGeocodeDialog(true);
            } else {
                Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
                restartCurrentFragmentLoader();
            }
        } else {
            showProducerGeocodeDialog(true);
        }

    } else if (requestCode == REQUEST_EDIT_REVIEW_LOCATION_GEOCODE
            && resultCode == AppCompatActivity.RESULT_OK) {
        if (mReviewLocationUris == null) {
            Log.e(LOG_TAG, "onActivityResult mReviewLocationUris == null! - should never happen");
            return;
        }

        if (mReviewLocationUris.isEmpty()) {
            Toast.makeText(MainActivity.this, "all geocoding done", Toast.LENGTH_SHORT).show();
            restartCurrentFragmentLoader();
        } else {
            showReviewLocationGeocodeDialog(true);
        }
    } else if (requestCode == ADD_REVIEW_REQUEST && resultCode == Activity.RESULT_OK && data != null) {
        // TODO bugfix: refresh current pager
        startActivity(new Intent(this, ShowReviewActivity.class).setData(data.getData()));
    }

    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.ez.gallery.ucrop.UCropActivity.java

/**
 * This method extracts all data from the incoming intent and setups views properly.
 *///from   w w  w  .j av  a2s. co  m
private void setImageData() {
    final Intent intent = getIntent();

    Uri inputUri = intent.getParcelableExtra(UCrop.EXTRA_INPUT_URI);
    mOutputUri = intent.getParcelableExtra(UCrop.EXTRA_OUTPUT_URI);
    processOptions(intent);

    if (inputUri != null && mOutputUri != null) {
        try {
            mGestureCropImageView.setImageUri(inputUri);
        } catch (Exception e) {
            Toast.makeText(getApplication(), "xxxx", Toast.LENGTH_SHORT).show();
            setResultException(e);
            finish();
        }
    } else {
        Toast.makeText(getApplication(), "fffff", Toast.LENGTH_SHORT).show();
        setResultException(new NullPointerException(getString(R.string.ucrop_error_input_data_is_absent)));
        finish();
    }

    if (intent.getBooleanExtra(UCrop.EXTRA_ASPECT_RATIO_SET, false)) {
        mWrapperStateAspectRatio.setVisibility(View.GONE);

        int aspectRatioX = intent.getIntExtra(UCrop.EXTRA_ASPECT_RATIO_X, 0);
        int aspectRatioY = intent.getIntExtra(UCrop.EXTRA_ASPECT_RATIO_Y, 0);

        if (aspectRatioX > 0 && aspectRatioY > 0) {
            mGestureCropImageView.setTargetAspectRatio(aspectRatioX / (float) aspectRatioY);
        } else {
            mGestureCropImageView.setTargetAspectRatio(CropImageView.SOURCE_IMAGE_ASPECT_RATIO);
        }
    }

    if (intent.getBooleanExtra(UCrop.EXTRA_MAX_SIZE_SET, false)) {
        int maxSizeX = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_X, 0);
        int maxSizeY = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_Y, 0);

        if (maxSizeX > 0 && maxSizeY > 0) {
            mGestureCropImageView.setMaxResultImageSizeX(maxSizeX);
            mGestureCropImageView.setMaxResultImageSizeY(maxSizeY);
        } else {
            Log.w(TAG, "EXTRA_MAX_SIZE_X and EXTRA_MAX_SIZE_Y must be greater than 0");
        }
    }
}

From source file:com.android.contacts.activities.ContactDetailActivity.java

/**
 * M: call back for create or update group in ContactDetailActivity.
 *//*  www . j  a  v a2s.c om*/
@Override
public void onServiceCompleted(Intent callbackIntent) {
    // / M: add for group new feature @{
    String action = callbackIntent.getAction();

    if (ACTION_UPDATE_COMPLETED.equals(action)) {
        long mRawContactId = callbackIntent.getLongExtra(ContactSaveService.EXTRA_RAW_CONTACTS_ID, -1);
        if (mRawContactId <= 0) {
            LogUtils.i(TAG, "[onServiceCompleted] save contact groups rawcontact id is " + mRawContactId
                    + " Group changes save failed.");
            return;
        }
    } else if (Intent.ACTION_INSERT.equals(action)) {
        boolean createGroup = callbackIntent.getBooleanExtra(ContactSaveService.CREATE_GROUP_COMP, false);
        if (createGroup) {
            ContactDetailFragment detailFragment = mContactDetailLayoutController.getDetailFragment();
            String groupName = callbackIntent.getStringExtra(ContactSaveService.EXTRA_NEW_GROUP_NAME);
            LogUtils.i(TAG, "[onServiceCompleted] create new group's name == " + groupName);
            detailFragment.setCreateNewGroupName(groupName);
        }

        if (callbackIntent.getData() == null) {
            LogUtils.i(TAG, "[onServiceCompleted] save contact group data is null, Save failed.");
            return;
        }
    }

    // toast save successful.
    MtkToast.toast(this, R.string.groupSavedToast);

    onNewIntent(callbackIntent);

}

From source file:gov.wa.wsdot.android.wsdot.service.FerriesTerminalSailingSpaceSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//w  ww . ja  v a  2  s. c om
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_terminal_sailing_space" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.SECOND_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(TERMINAL_SAILING_SPACE_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONArray array = new JSONArray(jsonFile);
            List<ContentValues> terminal = new ArrayList<ContentValues>();

            int numItems = array.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = array.getJSONObject(j);
                ContentValues sailingSpaceValues = new ContentValues();
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ID, item.getInt("TerminalID"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_NAME,
                        item.getString("TerminalName"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ABBREV,
                        item.getString("TerminalAbbrev"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES,
                        item.getString("DepartingSpaces"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED,
                        dateFormat.format(new Date(System.currentTimeMillis())));

                if (starred.contains(item.getInt("TerminalID"))) {
                    sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_IS_STARRED, 1);
                }

                terminal.add(sailingSpaceValues);
            }

            // Purge existing terminal sailing space items covered by incoming data
            resolver.delete(FerriesTerminalSailingSpace.CONTENT_URI, null, null);
            // Bulk insert all the new terminal sailing space items
            resolver.bulkInsert(FerriesTerminalSailingSpace.CONTENT_URI,
                    terminal.toArray(new ContentValues[terminal.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "ferries_terminal_sailing_space" });

            responseString = "OK";

        } catch (Exception e) {
            Log.e(TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent
            .setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_TERMINAL_SAILING_SPACE_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:com.google.android.exoplayer2.demo.MediaPlayerFragment.java

private void initializePlayer() {
    Intent intent = fragActivity.getIntent();
    boolean needNewPlayer = player == null;
    if (needNewPlayer) {
        boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
        UUID drmSchemeUuid = intent.hasExtra(DRM_SCHEME_UUID_EXTRA)
                ? UUID.fromString(intent.getStringExtra(DRM_SCHEME_UUID_EXTRA))
                : null;//w  ww  .  j a  v  a 2  s  . c  o m
        DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
        if (drmSchemeUuid != null) {
            String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
            String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
            try {
                drmSessionManager = buildDrmSessionManager(drmSchemeUuid, drmLicenseUrl,
                        keyRequestPropertiesArray);
            } catch (UnsupportedDrmException e) {
                int errorStringId = Util.SDK_INT < 18 ? R.string.error_drm_not_supported
                        : (e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                                ? R.string.error_drm_unsupported_scheme
                                : R.string.error_drm_unknown);
                showToast(errorStringId);
                return;
            }
        }

        @SimpleExoPlayer.ExtensionRendererMode
        int extensionRendererMode = ((ExplorerApplication) fragActivity.getApplication())
                .useExtensionRenderers()
                        ? (preferExtensionDecoders ? SimpleExoPlayer.EXTENSION_RENDERER_MODE_PREFER
                                : SimpleExoPlayer.EXTENSION_RENDERER_MODE_ON)
                        : SimpleExoPlayer.EXTENSION_RENDERER_MODE_OFF;
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
        trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
        trackSelectionHelper = new TrackSelectionHelper(trackSelector, videoTrackSelectionFactory);
        player = ExoPlayerFactory.newSimpleInstance(fragActivity, trackSelector, new DefaultLoadControl(),
                drmSessionManager, extensionRendererMode);
        player.addListener(this);

        eventLogger = new EventLogger(trackSelector);
        player.addListener(eventLogger);
        player.setAudioDebugListener(eventLogger);
        player.setVideoDebugListener(eventLogger);
        player.setMetadataOutput(eventLogger);

        simpleExoPlayerView.setPlayer(player);
        player.setPlayWhenReady(shouldAutoPlay);
        debugViewHelper = new DebugTextViewHelper(player, debugTextView);
        debugViewHelper.start();
    }
    if (needNewPlayer || needRetrySource) {
        String action = intent.getAction();
        Uri[] uris;
        String[] extensions;
        if (Intent.ACTION_VIEW.equals(action)) {
            uris = new Uri[] { intent.getData() };
            extensions = new String[] { intent.getStringExtra(EXTENSION_EXTRA) };
        } else if (ACTION_VIEW.equals(action)) {
            uris = new Uri[] { intent.getData() };
            extensions = new String[] { intent.getStringExtra(EXTENSION_EXTRA) };
        } else if (ACTION_VIEW_LIST.equals(action)) {
            String[] uriStrings = intent.getStringArrayExtra(URI_LIST_EXTRA);
            uris = new Uri[uriStrings.length];
            for (int i = 0; i < uriStrings.length; i++) {
                uris[i] = Uri.parse(uriStrings[i]);
            }
            extensions = intent.getStringArrayExtra(EXTENSION_LIST_EXTRA);
            if (extensions == null) {
                extensions = new String[uriStrings.length];
            }
        } else {
            if (!Intent.ACTION_MAIN.equals(action)) {
                showToast(getString(R.string.unexpected_intent_action, action));
            }
            return;
        }
        if (Util.maybeRequestReadExternalStoragePermission(fragActivity, uris)) {
            // The player will be reinitialized if the permission is granted.
            return;
        }
        MediaSource[] mediaSources = new MediaSource[uris.length];
        for (int i = 0; i < uris.length; i++) {
            mediaSources[i] = buildMediaSource(uris[i], extensions[i]);
        }
        MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
                : new ConcatenatingMediaSource(mediaSources);
        boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
        if (haveResumePosition) {
            player.seekTo(resumeWindow, resumePosition);
        }
        player.prepare(mediaSource, !haveResumePosition, false);
        needRetrySource = false;
        updateButtonVisibilities();
    }
}

From source file:com.example.maciej.mytask.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ADD_TASK_REQUEST) {
        if (resultCode == RESULT_OK) {
            String taskName = data.getStringExtra(NewTaskActivity.EXTRA_TASK_NAME);
            String taskDescription = data.getStringExtra(NewTaskActivity.EXTRA_TASK_DESCRIPTION);
            String taskDate = data.getStringExtra(NewTaskActivity.EXTRA_TASK_DATE);
            mNameList.add(taskName);/*  ww  w . j  a  va2s.  c  o  m*/
            mDescriptionList.add(taskDescription);
            mDateList.add(taskDate);
            mAdapter.notifyDataSetChanged();
        }
    }
    if (requestCode == MODIFY_TASK_REQUEST) {
        if (resultCode == RESULT_OK) {
            String taskName = data.getStringExtra(DescriptionActivity.EXTRA_TASK_NAME);
            String taskDescription = data.getStringExtra(DescriptionActivity.EXTRA_TASK_DESCRIPTION);
            String taskDate = data.getStringExtra(DescriptionActivity.EXTRA_TASK_DATE);
            String taskOldName = data.getStringExtra(DescriptionActivity.EXTRA_TASK_OLDNAME);
            Boolean taskDelete = data.getBooleanExtra(DescriptionActivity.EXTRA_TASK_DELETE, false);
            int index = mNameList.indexOf(taskOldName);
            if (taskDelete == false) {
                mNameList.set(index, taskName);
                mDescriptionList.set(index, taskDescription);
                mDateList.set(index, taskDate);
                mAdapter.notifyDataSetChanged();
            } else {
                deleteItem(index);
            }
        }
    }
}

From source file:com.android.contacts.activities.DialtactsActivity.java

/**
 * Returns true if the intent is due to hitting the green send key (hardware call button:
 * KEYCODE_CALL) while in a call.//from   www .  j  a  v a2s.  c o  m
 *
 * @param intent the intent that launched this activity
 * @param recentCallsRequest true if the intent is requesting to view recent calls
 * @return true if the intent is due to hitting the green send key while in a call
 */
private boolean isSendKeyWhileInCall(final Intent intent, final boolean recentCallsRequest) {
    // If there is a call in progress go to the call screen
    if (recentCallsRequest) {
        final boolean callKey = intent.getBooleanExtra("call_key", false);

        try {
            ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
            if (callKey && phone != null && phone.showCallScreen()) {
                return true;
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to handle send while in call", e);
        }
    }

    return false;
}

From source file:com.ichi2.anki2.CardBrowser.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    View mainView = getLayoutInflater().inflate(R.layout.card_browser, null);
    setContentView(mainView);// ww w  .  j  a  v  a2s .com
    Themes.setContentStyle(mainView, Themes.CALLER_CARDBROWSER);

    mCol = AnkiDroidApp.getCol();
    if (mCol == null) {
        reloadCollection(savedInstanceState);
        return;
    }
    mDeckNames = new HashMap<String, String>();
    for (long did : mCol.getDecks().allIds()) {
        mDeckNames.put(String.valueOf(did), mCol.getDecks().name(did));
    }
    registerExternalStorageListener();

    Intent i = getIntent();
    mWholeCollection = i.hasExtra("fromDeckpicker") && i.getBooleanExtra("fromDeckpicker", false);

    mBackground = Themes.getCardBrowserBackground();

    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
    int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
    String sflCustomFont = preferences.getString("browserEditorFont", "");
    mPrefFixArabic = preferences.getBoolean("fixArabicText", false);

    Resources res = getResources();
    mOrderByFields = res.getStringArray(R.array.card_browser_order_labels);
    try {
        mOrder = CARD_ORDER_NONE;
        String colOrder = mCol.getConf().getString("sortType");
        for (int c = 0; c < fSortTypes.length; ++c) {
            if (fSortTypes[c].equals(colOrder)) {
                mOrder = c;
                break;
            }
        }
        if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
            mOrder = 0;
        }
        mOrderAsc = Upgrade.upgradeJSONIfNecessary(mCol, mCol.getConf(), "sortBackwards", false);
        // default to descending for non-text fields
        if (fSortTypes[mOrder].equals("noteFld")) {
            mOrderAsc = !mOrderAsc;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    mCards = new ArrayList<HashMap<String, String>>();
    mCardsListView = (ListView) findViewById(R.id.card_browser_list);

    mCardsAdapter = new SizeControlledListAdapter(this, mCards, R.layout.card_item,
            new String[] { "sfld", "deck", "flags" },
            new int[] { R.id.card_sfld, R.id.card_deck, R.id.card_item }, sflRelativeFontSize, sflCustomFont);
    mCardsAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object arg1, String text) {
            if (view.getId() == R.id.card_item) {
                int which = BACKGROUND_NORMAL;
                if (text.equals("1")) {
                    which = BACKGROUND_SUSPENDED;
                } else if (text.equals("2")) {
                    which = BACKGROUND_MARKED;
                } else if (text.equals("3")) {
                    which = BACKGROUND_MARKED_SUSPENDED;
                }
                view.setBackgroundResource(mBackground[which]);
                return true;
            } else if (view.getId() == R.id.card_deck && text.length() > 0) {
                view.setVisibility(View.VISIBLE);
            }
            return false;
        }
    });

    mCardsListView.setAdapter(mCardsAdapter);
    mCardsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent editCard = new Intent(CardBrowser.this, CardEditor.class);
            editCard.putExtra(CardEditor.EXTRA_CALLER, CardEditor.CALLER_CARDBROWSER_EDIT);
            mPositionInCardsList = position;
            long cardId = Long.parseLong(mCards.get(mPositionInCardsList).get("id"));
            sCardBrowserCard = mCol.getCard(cardId);
            startActivityForResult(editCard, EDIT_CARD);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT);
            }
        }
    });
    registerForContextMenu(mCardsListView);

    mSearchEditText = (EditText) findViewById(R.id.card_browser_search);
    mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                onSearch();
                return true;
            }
            return false;
        }
    });
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    mSearchButton = (ImageButton) findViewById(R.id.card_browser_search_button);
    mSearchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSearch();
        }
    });

    mSearchTerms = "";
    if (mWholeCollection) {
        mRestrictOnDeck = "";
        setTitle(res.getString(R.string.card_browser_all_decks));
    } else {
        try {
            String deckName = mCol.getDecks().current().getString("name");
            mRestrictOnDeck = "deck:'" + deckName + "' ";
            setTitle(deckName);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    mSelectedTags = new HashSet<String>();

    if (!preferences.getBoolean("cardBrowserNoSearchOnOpen", false)) {
        searchCards();
    }
}

From source file:com.gimranov.zandy.app.ItemActivity.java

/**
 * Called when the activity is first created.
 *///ww  w . j av a 2  s.c  o  m
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String persistedSort = Persistence.read(SORT_CHOICE);
    if (persistedSort != null)
        sortBy = persistedSort;

    db = new Database(this);

    setContentView(R.layout.items);

    Intent intent = getIntent();
    collectionKey = intent.getStringExtra("com.gimranov.zandy.app.collectionKey");

    ItemCollection coll = ItemCollection.load(collectionKey, db);
    APIRequest req;

    if (coll != null) {
        req = APIRequest.fetchItems(coll, false, new ServerCredentials(this));
    } else {
        req = APIRequest.fetchItems(false, new ServerCredentials(this));
    }

    prepareAdapter();

    ItemAdapter adapter = (ItemAdapter) getListAdapter();
    Cursor cur = adapter.getCursor();

    if (intent.getBooleanExtra("com.gimranov.zandy.app.rerequest", false) || cur == null
            || cur.getCount() == 0) {

        if (!ServerCredentials.check(getBaseContext())) {
            Toast.makeText(getBaseContext(), getResources().getString(R.string.sync_log_in_first),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, getResources().getString(R.string.collection_empty), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "Running a request to populate missing items");
        ZoteroAPITask task = new ZoteroAPITask(this);
        req.setHandler(mEvent);
        task.execute(req);

    }

    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // If we have a click on an item, do something...
            ItemAdapter adapter = (ItemAdapter) parent.getAdapter();
            Cursor cur = adapter.getCursor();
            // Place the cursor at the selected item
            if (cur.moveToPosition(position)) {
                // and load an activity for the item
                Item item = Item.load(cur);

                Log.d(TAG, "Loading item data with key: " + item.getKey());
                // We create and issue a specified intent with the necessary data
                Intent i = new Intent(getBaseContext(), ItemDataActivity.class);
                i.putExtra("com.gimranov.zandy.app.itemKey", item.getKey());
                i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId);
                startActivity(i);
            } else {
                // failed to move cursor-- show a toast
                TextView tvTitle = (TextView) view.findViewById(R.id.item_title);
                Toast.makeText(getApplicationContext(),
                        getResources().getString(R.string.cant_open_item, tvTitle.getText()),
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
}

From source file:com.hichinaschool.flashcards.anki.CardBrowser.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    Themes.applyTheme(this);
    super.onCreate(savedInstanceState);

    View mainView = getLayoutInflater().inflate(R.layout.card_browser, null);
    setContentView(mainView);/* w  w w.j  av a 2 s. com*/
    Themes.setContentStyle(mainView, Themes.CALLER_CARDBROWSER);

    mCol = AnkiDroidApp.getCol();
    if (mCol == null) {
        reloadCollection(savedInstanceState);
        return;
    }
    mDeckNames = new HashMap<String, String>();
    for (long did : mCol.getDecks().allIds()) {
        mDeckNames.put(String.valueOf(did), mCol.getDecks().name(did));
    }
    registerExternalStorageListener();

    Intent i = getIntent();
    mWholeCollection = i.hasExtra("fromDeckpicker") && i.getBooleanExtra("fromDeckpicker", false);

    mBackground = Themes.getCardBrowserBackground();

    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
    int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
    String sflCustomFont = preferences.getString("browserEditorFont", "");
    mPrefFixArabic = preferences.getBoolean("fixArabicText", false);

    Resources res = getResources();
    mOrderByFields = res.getStringArray(R.array.card_browser_order_labels);
    try {
        mOrder = CARD_ORDER_NONE;
        String colOrder = mCol.getConf().getString("sortType");
        for (int c = 0; c < fSortTypes.length; ++c) {
            if (fSortTypes[c].equals(colOrder)) {
                mOrder = c;
                break;
            }
        }
        if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
            mOrder = 0;
        }
        mOrderAsc = Upgrade.upgradeJSONIfNecessary(mCol, mCol.getConf(), "sortBackwards", false);
        // default to descending for non-text fields
        if (fSortTypes[mOrder].equals("noteFld")) {
            mOrderAsc = !mOrderAsc;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    mCards = new ArrayList<HashMap<String, String>>();
    mCardsListView = (ListView) findViewById(R.id.card_browser_list);

    mCardsAdapter = new SizeControlledListAdapter(this, mCards, R.layout.card_item,
            new String[] { "sfld", "deck", "flags" },
            new int[] { R.id.card_sfld, R.id.card_deck, R.id.card_item }, sflRelativeFontSize, sflCustomFont);
    mCardsAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object arg1, String text) {
            if (view.getId() == R.id.card_item) {
                int which = BACKGROUND_NORMAL;
                if (text.equals("1")) {
                    which = BACKGROUND_SUSPENDED;
                } else if (text.equals("2")) {
                    which = BACKGROUND_MARKED;
                } else if (text.equals("3")) {
                    which = BACKGROUND_MARKED_SUSPENDED;
                }
                view.setBackgroundResource(mBackground[which]);
                return true;
            } else if (view.getId() == R.id.card_deck && text.length() > 0) {
                view.setVisibility(View.VISIBLE);
            }
            return false;
        }
    });

    mCardsListView.setAdapter(mCardsAdapter);
    mCardsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mPositionInCardsList = position;
            long cardId = Long.parseLong(mCards.get(mPositionInCardsList).get("id"));
            sCardBrowserCard = mCol.getCard(cardId);
            Intent editCard = new Intent(CardBrowser.this, CardEditor.class);
            editCard.putExtra(CardEditor.EXTRA_CALLER, CardEditor.CALLER_CARDBROWSER_EDIT);
            editCard.putExtra(CardEditor.EXTRA_CARD_ID, sCardBrowserCard.getId());
            startActivityForResult(editCard, EDIT_CARD);
            if (AnkiDroidApp.SDK_VERSION > 4) {
                ActivityTransitionAnimation.slide(CardBrowser.this, ActivityTransitionAnimation.LEFT);
            }
        }
    });
    registerForContextMenu(mCardsListView);

    mSearchEditText = (EditText) findViewById(R.id.card_browser_search);
    mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                onSearch();
                return true;
            }
            return false;
        }
    });
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    mSearchButton = (ImageButton) findViewById(R.id.card_browser_search_button);
    mSearchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onSearch();
        }
    });

    mSearchTerms = "";
    if (mWholeCollection) {
        mRestrictOnDeck = "";
        setTitle(res.getString(R.string.card_browser_all_decks));
    } else {
        try {
            String deckName = mCol.getDecks().current().getString("name");
            mRestrictOnDeck = "deck:'" + deckName + "' ";
            setTitle(deckName);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    mSelectedTags = new HashSet<String>();

    if (!preferences.getBoolean("cardBrowserNoSearchOnOpen", false)) {
        searchCards();
    }
}