Example usage for android.graphics Color parseColor

List of usage examples for android.graphics Color parseColor

Introduction

In this page you can find the example usage for android.graphics Color parseColor.

Prototype

@ColorInt
public static int parseColor(@Size(min = 1) String colorString) 

Source Link

Document

Parse the color string, and return the corresponding color-int.

Usage

From source file:de.teambluebaer.patientix.activities.StartActivity.java

/**
 * This Method defines what happens if you press the 'Aktualisieren' button.
 * The tabletID will be set to the parametermap to have a parameter for the
 * http post of the Restfullhelper. In the next step  if we recieve the
 * responseCode 200 the JavaStructBuilder is called that the recived String
 * can be made ready for working with. After that the patientdata will be
 * shown on the screen.// w w w  .ja v  a 2 s .co m
 * In the case if there are no data to work with or the tablet has no
 * connection to the server there will be some toasts shown to display
 * the error.
 *
 * @param v default parameter to change something of the view
 */
public void onClickUpdateButton(View v) {
    RestfulHelper restfulHelper = new RestfulHelper();
    textViewPatientName.setText("");
    textViewPatientBirth.setText("");
    textViewExameName.setText("");
    Constants.GLOBALMETAANDFORM = new MetaAndForm();
    buttonStart.setVisibility(View.INVISIBLE);
    buttonStart.setClickable(false);

    parameterMap.clear();
    parameterMap.add(new BasicNameValuePair("tabletID", TABLET_ID));

    Log.d("tabletID", TABLET_ID);
    //send the request to server
    responseCode = restfulHelper.executeRequest("formula", parameterMap);

    //changing some things on the layout
    Log.d("ResponseCode", responseCode + "");
    Log.d("ResponseString", restfulHelper.responseString);
    if (responseCode == 200) {
        if (!restfulHelper.responseString.isEmpty() || restfulHelper.responseString.length() < 10) {
            try {
                String xmlString = restfulHelper.responseString;
                Log.d("ResponseString: ", restfulHelper.responseString);
                JavaStrucBuilder strucBuilder = new JavaStrucBuilder();
                Constants.GLOBALMETAANDFORM = strucBuilder.buildStruc(xmlString);

                Toast.makeText(getBaseContext(), "Fragebogen wurde gespeichert!", Toast.LENGTH_SHORT).show();

                textViewPatientName.setText(Constants.GLOBALMETAANDFORM.getMeta().getPatientLastName() + ", "
                        + Constants.GLOBALMETAANDFORM.getMeta().getPatientFirstName());
                textViewPatientName.setBackgroundColor(Color.parseColor("#ffffff"));
                textViewPatientBirth.setBackgroundColor(Color.parseColor("#ffffff"));
                textViewExameName.setBackgroundColor(Color.parseColor("#ffffff"));
                String birthDate = "";
                if (!Constants.GLOBALMETAANDFORM.getMeta().getPatientBithDate().equals("Unbekannt")) {
                    birthDate = getbirthDate();
                }
                textViewPatientBirth.setText("Geb. " + birthDate);

                textViewExameName.setText(Constants.GLOBALMETAANDFORM.getMeta().getExameName());
                buttonStart.setVisibility(View.VISIBLE);
                buttonStart.setClickable(true);

            } catch (Exception e) {
                Log.d("FileSaveExeption", e.toString());
                Toast.makeText(getBaseContext(), "Fehler beim Speichern des Fragebogens", Toast.LENGTH_LONG)
                        .show();
            }
            Constants.ISSEND = false;
        } else {
            Toast.makeText(getBaseContext(), "Keine Verbindung zum Server!", Toast.LENGTH_LONG).show();
        }

    } else if (404 == responseCode) {
        Toast.makeText(StartActivity.this, "Keine Daten fr dieses Tablet vorhanden", Toast.LENGTH_LONG)
                .show();
    } else {
        Toast.makeText(StartActivity.this, "Kein Verbindung zum Server! Fehlercode: " + responseCode,
                Toast.LENGTH_LONG).show();
    }
}

From source file:com.eugene.fithealthmaingit.UI.ChooseAddMealTabsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_search_add_item_pager, container, false);
    // Change the status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window w = getActivity().getWindow();
        w.setStatusBarColor(getResources().getColor(R.color.accent_dark));
    }//from   w  w  w  . ja v a 2  s . c  o  m

    Bundle extras = getActivity().getIntent().getExtras();
    if (extras != null) {
        mealType = extras.getString(Globals.MEAL_TYPE);
        page = extras.getInt("PAGE");
    }

    card_search_manual = (CardView) v.findViewById(R.id.card_search_manual);
    card_search_fav = (CardView) v.findViewById(R.id.card_search_fav);

    // Initiate Toolbar
    Toolbar mToolbar = (Toolbar) v.findViewById(R.id.toolbar_search_main);
    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(mToolbar.getWindowToken(), 0);
    mToolbar.setNavigationIcon(R.mipmap.ic_arrow_back);
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().finish();
        }
    });
    mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.action_search)
                mCallbacks.searchClicked();
            if (menuItem.getItemId() == R.id.action_manual) {
                Intent i = new Intent(getActivity(), ManualEntryActivity.class);
                i.putExtra(Globals.MEAL_TYPE, mealType);
                startActivity(i);
            }
            return false;
        }
    });
    TextViewFont txtTitle = (TextViewFont) v.findViewById(R.id.txtTitle);
    if (txtTitle != null)
        txtTitle.setText(mealType);
    mToolbar.inflateMenu(R.menu.menu_search_add);

    // Hide keyboard
    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(mToolbar.getWindowToken(), 0);

    // Initiate Pager and Tabs
    ChooseAddMealPagerAdapter myPagerAdapterAdd = new ChooseAddMealPagerAdapter();
    ViewPager mViewPager = (ViewPager) v.findViewById(R.id.pager);
    TabLayout tabs = (TabLayout) v.findViewById(R.id.tabs);
    tabs.setTabTextColors(Color.parseColor("#80ffffff"), Color.parseColor("#ffffff"));
    tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
    mViewPager.setAdapter(myPagerAdapterAdd);
    mViewPager.setOffscreenPageLimit(4);
    tabs.setupWithViewPager(mViewPager);
    mViewPager.setCurrentItem(page);
    // Initiate ListView and their adapters
    ListView mListRecentSearches = (ListView) v.findViewById(R.id.listRecentSearches);
    mListFavorites = (ListView) v.findViewById(R.id.listFavorites);
    listViewManual = (ListView) v.findViewById(R.id.listViewManual);
    llNoRecentFav = (LinearLayout) v.findViewById(R.id.llNoRecentFav);
    llNoRecentManual = (LinearLayout) v.findViewById(R.id.llNoRecentManual);
    llNoRecentSearch = (LinearLayout) v.findViewById(R.id.llNoRecentSearch);
    mRecentLogAdapter = new LogQuickSearchSimpleAdapter(getActivity(), 0, LogQuickSearch.all());
    mListRecentSearches.setAdapter(mRecentLogAdapter);
    mListRecentSearches.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            LogQuickSearch recentLog = mRecentLogAdapter.getItem(position);
            mCallbacks.recentSearchClicked(recentLog.getName());
        }
    });

    mLogAdapterFavorite = new LogAdapterAll(getActivity(), 0, LogMeal.logSortByFavorite("favorite"));
    ViewGroup headerFav = (ViewGroup) inflater.inflate(R.layout.list_header_search_favorites, listViewManual,
            false);
    mListFavorites.addHeaderView(headerFav, null, false);
    mListFavorites.setAdapter(mLogAdapterFavorite);
    mListFavorites.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(searchManual.getWindowToken(), 0);
            LogMeal logMeal = mLogAdapterFavorite.getItem(position - 1);
            Intent i = new Intent(getActivity(), SaveSearchAddItemActivityMain.class);
            i.putExtra(Globals.MEAL_TYPE, mealType);
            i.putExtra(Globals.MEAL_ID, logMeal.getMealId());
            i.putExtra(Globals.MEAL_BRAND, logMeal.getBrand());
            i.putExtra(Globals.MEAL_FAVORITE, logMeal.getFavorite());
            startActivity(i);
        }
    });

    mLogAdapterManual = new LogAdapterManual(getActivity(), 0, LogManual.all(), mealType);
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header_search, listViewManual, false);
    listViewManual.addHeaderView(header, null, false);
    listViewManual.setAdapter(mLogAdapterManual);
    listViewManual.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(searchManual.getWindowToken(), 0);
            LogManual logManual = mLogAdapterManual.getItem(position - 1);
            Intent i = new Intent(getActivity(), ManualEntrySaveMealActivity.class);
            i.putExtra(Globals.MEAL_TYPE, mealType);
            i.putExtra(Globals.MEAL_ID, logManual.getMealId());
            startActivity(i);
        }
    });
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        ((RelativeLayout.LayoutParams) card_search_manual.getLayoutParams()).setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
        ((RelativeLayout.LayoutParams) card_search_fav.getLayoutParams()).setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
        headerFav.setPadding(0, 0, 0, Equations.dpToPx(getActivity(), 16));
        header.setPadding(0, 0, 0, Equations.dpToPx(getActivity(), 16));
    }

    searchManualEntry();
    searchFav();

    /**
     * TODO RECIPE
     */
    Button btnRecipe = (Button) v.findViewById(R.id.btnRecipe);
    btnRecipe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogRecipeHolder newRecipe = new LogRecipeHolder();
            newRecipe.setDate(new Date());
            newRecipe.setMealChoice(mealType);
            newRecipe.setMealName("Recipe");
            newRecipe.save();
            Intent i = new Intent(getActivity(), RecipeActivity.class);
            i.putExtra(Globals.MEAL_ID, newRecipe.getId());
            i.putExtra(Globals.MEAL_TYPE, mealType);
            startActivity(i);
        }
    });
    logAdapterMealRecipe = new LogRecipeHolderAdapter(getActivity(), 0, LogRecipeHolder.all());
    listRecipes = (ListView) v.findViewById(R.id.listRecipes);
    listRecipes.setAdapter(logAdapterMealRecipe);
    listRecipes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            LogRecipeHolder newRecipe = logAdapterMealRecipe.getItem(position);
            Intent i = new Intent(getActivity(), RecipeActivity.class);
            i.putExtra(Globals.MEAL_ID, newRecipe.getId());
            i.putExtra(Globals.MEAL_TYPE, mealType);
            startActivity(i);
        }
    });

    searchManual = (Button) v.findViewById(R.id.searchManual);
    searchManual.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handleSearchManual();
        }
    });
    searchFavorite = (Button) v.findViewById(R.id.searchFav);
    searchFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handleSearchFavorite();
        }
    });

    updateListView();
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(searchManual.getWindowToken(), 0);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
    return v;
}

From source file:com.androguide.honamicontrol.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override/*from w w  w . j  av a 2 s.  c o  m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);
    headers.add("Welcome");
    headers.add("Kernel Control");
    headers.add("Sound Control");
    headers.add("Touch Screen");
    headers.add("Help Center");

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    ArrayAdapter<String> pimpAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item,
            mDrawerHeaders);
    mDrawerList.setAdapter(pimpAdapter);

    View child = mDrawerList.getChildAt(mDrawerList.getFirstVisiblePosition());

    if (child != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        child.setBackground(getColouredTouchFeedback());
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    /**
     * ActionBarDrawerToggle ties together the proper interactions between
     * the sliding drawer and the action bar app icon
     */
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.open_drawer,
            R.string.close_drawer) {

        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /** Tabs adapter using the PagerSlidingStrip library */
    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);
    MyPagerAdapter adapter = new MyPagerAdapter(this.getSupportFragmentManager());
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            getResources().getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);
    tabs.setOnPageChangeListener(this);

    changeColor(Color.parseColor(mAppColor));
    pager.setOffscreenPageLimit(5);
}

From source file:com.example.grayapps.contextaware.BarFragment.java

/**
 * Chart 1//from   w w  w. j a v  a  2  s.  c om
 */

public void produceOne(ChartView chart, Runnable action) {
    BarChartView barChart = (BarChartView) chart;

    barChart.setOnEntryClickListener(new OnEntryClickListener() {
        @Override
        public void onClick(int setIndex, int entryIndex, Rect rect) {
            System.out.println("OnClick " + rect.left);
        }
    });

    // Tooltip tooltip = new Tooltip(getActivity(), R.layout.barchart_one_tooltip);
    //if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    //   tooltip.setEnterAnimation(PropertyValuesHolder.ofFloat(View.ALPHA, 1));
    //   tooltip.setExitAnimation(PropertyValuesHolder.ofFloat(View.ALPHA, 0));
    // }
    // barChart.setTooltips(tooltip);
    if (!mRealEvent) {
        mValuesOne[0][0] = Float.valueOf(String.valueOf(10 * Math.random()));
        mValuesOne[0][1] = Float.valueOf(String.valueOf(10 * Math.random()));
    }
    BarSet barSet = new BarSet(mLabelsOne, mValuesOne[0]);
    barSet.setColor(Color.parseColor(mStressColor));
    /*  for (int z = 0; z < mValuesOne[0].length; z++) {
       if (mValuesOne[0][z] < 2.5) {
        barSet.getEntry(z).setColor(Color.parseColor("#2c93d0"));//blue
    } else if (mValuesOne[0][z] < 5) {
        barSet.getEntry(z).setColor(Color.parseColor("#3ac298"));//green
    } else if (mValuesOne[0][z] >= 7.5) {
        barSet.getEntry(z).setColor(Color.parseColor("#db0c42"));//red
    }
    //default: purple
     }*//**/

    barChart.addData(barSet);
    barChart.setBarSpacing(Tools.fromDpToPx(35));

    barChart.setBorderSpacing(5).setAxisBorderValues(0, 10, 2).setYAxis(false)
            .setXLabels(XController.LabelPosition.OUTSIDE).setYLabels(YController.LabelPosition.NONE)
            .setLabelsColor(Color.parseColor("#fffdfdfd")).setFontSize(28)
            .setAxisColor(Color.parseColor("#a0fdfdfd"));

    int[] order = { 0, 1 };//, 0, 4};
    final Runnable auxAction = action;
    Runnable chartOneAction = new Runnable() {
        @Override
        public void run() {
            //showTooltipOne();
            auxAction.run();
        }
    };
    barChart.show(new Animation().setOverlap(.5f, order).setEndAction(chartOneAction))
    //.show()
    ;
}

From source file:com.timemachine.controller.ControllerActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);

    // Associate searchable configuration with the SearchView
    // Get the SearchView and set the searchable configuration
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    // Change the text color in the search view
    int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    searchTextView = (TextView) searchView.findViewById(id);
    searchTextView.setHintTextColor(Color.parseColor("#80ffffff"));
    searchTextView.setTextColor(Color.parseColor("#ffffff"));

    return super.onCreateOptionsMenu(menu);
}

From source file:com.cflp.zwl.view.TabPageIndicator.java

@Override
public void onPageSelected(int arg0) {
    setCurrentItem(arg0);//  w w  w. j  a  v a2  s.  c  o  m
    final int oldSelected = mViewPager.getCurrentItem();
    TabView oldtab = (TabView) mTabLayout.getChildAt(currentId);
    oldtab.setTextColor(Color.parseColor("#404040"));
    oldtab.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
    TabView newtab = (TabView) mTabLayout.getChildAt(arg0);
    currentId = arg0;
    if (mListener != null) {

        mListener.onPageSelected(arg0);
    }
}

From source file:com.njlabs.amrita.aid.info.Calender.java

@Override
public void init(Bundle savedInstanceState) {
    setupLayout(R.layout.activity_calender, Color.parseColor("#fe5352"));

    final Calender thisContext = this;

    descriptions = new HashMap<>();
    backgroundColors = new HashMap<>();
    textColors = new HashMap<>();

    SharedPreferences preferences = getSharedPreferences("app_extra", Context.MODE_PRIVATE);
    Boolean AgreeStatus = preferences.getBoolean("calender_agree", false);

    if (!AgreeStatus) {
        AlertDialog.Builder builder = new AlertDialog.Builder(thisContext);
        builder.setTitle("Academic Calender").setIcon(R.drawable.ic_action_info_small).setMessage(
                "Red denotes that it's an Exam day. Blue denotes an event (not a Holiday). Whereas Green denotes a Holiday. I'm not resposibile for the accuracy of the dates")
                .setCancelable(false).setPositiveButton("I Agree", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        SharedPreferences preferences = getSharedPreferences("app_extra", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putBoolean("calender_agree", true);
                        editor.apply();//from   ww  w  .ja v a 2  s.  co m
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    caldroidFragment = new CaldroidFragment();

    if (savedInstanceState != null) {
        caldroidFragment.restoreStatesFromKey(savedInstanceState, "CALDROID_SAVED_STATE");
    } else {
        Bundle args = new Bundle();
        Calendar cal = Calendar.getInstance();
        args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
        args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
        args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true);
        caldroidFragment.setArguments(args);
    }

    setCustomResourceForDates();

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar, caldroidFragment);
    t.commit();

    final CaldroidListener listener = new CaldroidListener() {
        @Override
        public void onSelectDate(Date date, View view) {
            if (!formatter.format(date).equals("")) {
                String description = descriptions.get(formatter.format(date));
                if (description != null && !description.equals("")) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(thisContext);
                    builder.setMessage(description).setCancelable(true).setPositiveButton("Close",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }
    };
    caldroidFragment.setCaldroidListener(listener);
}

From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteSessionsHandler.java

@Override
public ArrayList<ContentProviderOperation> parse(ArrayList<JSONArray> entries, ContentResolver resolver)
        throws JSONException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
    final HashSet<String> sessionIds = Sets.newHashSet();
    final HashSet<String> trackIds = Sets.newHashSet();
    final HashMap<String, HashSet<String>> sessionSpeakerIds = Maps.newHashMap();
    final HashMap<String, HashSet<String>> sessionTagIds = Maps.newHashMap();

    int nrEntries = 0;
    for (JSONArray sessions : entries) {
        Log.d(TAG, "Retrieved " + sessions.length() + " presentation entries.");
        nrEntries += sessions.length();/*from  w w  w.  j a  v a  2 s  .c om*/

        for (int i = 0; i < sessions.length(); i++) {
            JSONObject session = sessions.getJSONObject(i);
            String id = session.getString("id");

            final String sessionId = sanitizeId(id);
            final Uri sessionUri = Sessions.buildSessionUri(sessionId);
            sessionIds.add(sessionId);
            int isStarred = isStarred(sessionUri, resolver);

            boolean sessionUpdated = false;
            boolean newSession = false;
            ContentProviderOperation.Builder builder;
            if (isRowExisting(sessionUri, SessionsQuery.PROJECTION, resolver)) {
                builder = ContentProviderOperation.newUpdate(sessionUri);
                builder.withValue(Sessions.NEW, false);
                sessionUpdated = isSessionUpdated(sessionUri, session, resolver);
                if (isRemoteSync()) {
                    builder.withValue(Sessions.UPDATED, sessionUpdated);
                }
            } else {
                newSession = true;
                builder = ContentProviderOperation.newInsert(Sessions.CONTENT_URI);
                builder.withValue(Sessions.SESSION_ID, sessionId);
                if (!isLocalSync()) {
                    builder.withValue(Sessions.NEW, true);
                }
            }

            final String type = session.getString("type");
            if (newSession || sessionUpdated) {
                builder.withValue(Sessions.TITLE, session.getString("title"));
                builder.withValue(Sessions.EXPERIENCE, session.getString("experience"));
                builder.withValue(Sessions.TYPE, type);
                builder.withValue(Sessions.SUMMARY, session.getString("summary"));
                builder.withValue(Sessions.STARRED, isStarred);
            }
            builder.withValue(Sessions.TYPE_ID, getTypeId(type));

            batch.add(builder.build());

            if (session.has("track")) {
                final String trackName = session.getString("track");
                final String trackId = Tracks.generateTrackId(trackName);
                final Uri trackUri = Tracks.buildTrackUri(trackId);

                if (!trackIds.contains(trackId)) {
                    trackIds.add(trackId);

                    ContentProviderOperation.Builder trackBuilder;
                    if (isRowExisting(Tracks.buildTrackUri(trackId), TracksQuery.PROJECTION, resolver)) {
                        trackBuilder = ContentProviderOperation.newUpdate(trackUri);
                    } else {
                        trackBuilder = ContentProviderOperation.newInsert(Tracks.CONTENT_URI);
                        trackBuilder.withValue(Tracks.TRACK_ID, trackId);
                    }

                    trackBuilder.withValue(Tracks.TRACK_NAME, trackName);
                    final int color = Color.parseColor(getTrackColor(trackId));
                    trackBuilder.withValue(Tracks.TRACK_COLOR, color);
                    batch.add(trackBuilder.build());
                }

                if (newSession || sessionUpdated) {
                    builder.withValue(Sessions.TRACK_ID, trackId);
                }
            }

            if (session.has("speakers")) {
                final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
                final JSONArray speakers = session.getJSONArray("speakers");
                final HashSet<String> speakerIds = Sets.newHashSet();

                if (!isLocalSync()) {
                    final boolean sessionSpeakersUpdated = isSessionSpeakersUpdated(speakerSessionsUri,
                            speakers, resolver);
                    if (sessionSpeakersUpdated) {
                        Log.d(TAG, "Speakers of session with id " + sessionId + " was udpated.");
                        batch.add(ContentProviderOperation.newUpdate(sessionUri)
                                .withValue(Sessions.UPDATED, true).build());
                    }
                }

                for (int j = 0; j < speakers.length(); j++) {
                    JSONObject speaker = speakers.getJSONObject(j);

                    final Uri speakerUri = Uri.parse(speaker.getString("speakerUri"));
                    final String speakerId = speakerUri.getLastPathSegment();
                    speakerIds.add(speakerId);

                    batch.add(ContentProviderOperation.newInsert(speakerSessionsUri)
                            .withValue(SessionsSpeakers.SPEAKER_ID, speakerId)
                            .withValue(SessionsSpeakers.SESSION_ID, sessionId).build());
                }

                sessionSpeakerIds.put(sessionId, speakerIds);
            }

            if (session.has("tags")) {
                final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
                final JSONArray tags = session.getJSONArray("tags");
                final HashSet<String> tagIds = Sets.newHashSet();

                for (int j = 0; j < tags.length(); j++) {
                    JSONObject tag = tags.getJSONObject(j);
                    final String tagName = tag.getString("name").toLowerCase();
                    final String tagId = Tags.generateTagId(tagName);
                    tagIds.add(tagId);

                    batch.add(ContentProviderOperation.newInsert(Tags.CONTENT_URI).withValue(Tags.TAG_ID, tagId)
                            .withValue(Tags.TAG_NAME, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI)
                            .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, tagName).build());

                    batch.add(ContentProviderOperation.newInsert(tagSessionsUri)
                            .withValue(SessionsTags.TAG_ID, tagId).withValue(SessionsTags.SESSION_ID, sessionId)
                            .build());
                }

                sessionTagIds.put(sessionId, tagIds);
            }
        }
    }

    if (isRemoteSync() && nrEntries > 0) {
        for (Entry<String, HashSet<String>> entry : sessionSpeakerIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> speakerIds = entry.getValue();
            final Uri speakerSessionsUri = Sessions.buildSpeakersDirUri(sessionId);
            HashSet<String> lostSpeakerIds = getLostIds(speakerIds, speakerSessionsUri,
                    SpeakersQuery.PROJECTION, SpeakersQuery.SPEAKER_ID, resolver);
            for (String lostSpeakerId : lostSpeakerIds) {
                final Uri deleteUri = Sessions.buildSessionSpeakerUri(sessionId, lostSpeakerId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        for (Entry<String, HashSet<String>> entry : sessionTagIds.entrySet()) {
            String sessionId = entry.getKey();
            HashSet<String> tagIds = entry.getValue();
            final Uri tagSessionsUri = Sessions.buildTagsDirUri(sessionId);
            HashSet<String> lostTagIds = getLostIds(tagIds, tagSessionsUri, TagsQuery.PROJECTION,
                    TagsQuery.TAG_ID, resolver);
            for (String lostTagId : lostTagIds) {
                final Uri deleteUri = Sessions.buildSessionTagUri(sessionId, lostTagId);
                batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            }
        }

        HashSet<String> lostTrackIds = getLostIds(trackIds, Tracks.CONTENT_URI, TracksQuery.PROJECTION,
                TracksQuery.TRACK_ID, resolver);
        for (String lostTrackId : lostTrackIds) {
            Uri deleteUri = Tracks.buildSessionsUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Tracks.buildTrackUri(lostTrackId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
        HashSet<String> lostSessionIds = getLostIds(sessionIds, Sessions.CONTENT_URI, SessionsQuery.PROJECTION,
                SessionsQuery.SESSION_ID, resolver);
        for (String lostSessionId : lostSessionIds) {
            Uri deleteUri = Sessions.buildSpeakersDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildTagsDirUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            deleteUri = Sessions.buildSessionUri(lostSessionId);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
        }
    }

    return batch;
}

From source file:com.cryart.sabbathschool.view.SSReadingActivity.java

public void updateColorScheme() {
    int primaryColor = Color.parseColor(SSColorTheme.getInstance().getColorPrimary());
    binding.ssReadingAppBar.ssReadingCollapsingToolbar.setContentScrimColor(primaryColor);
    binding.ssReadingAppBar.ssReadingCollapsingToolbar.setBackgroundColor(primaryColor);
    binding.ssReadingSheetHeader.setBackgroundColor(primaryColor);

    updateWindowColorScheme(false);/*from ww w . j  ava 2s.c o  m*/
}