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:com.amaze.filemanager.fragments.BookmarksManager.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setHasOptionsMenu(false);/*  w w  w  .  jav a  2 s . co m*/
    setRetainInstance(false);
    s = new Shortcuts(getActivity());
    Calendar calendar = Calendar.getInstance();
    Sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    theme = Integer.parseInt(Sp.getString("theme", "0"));
    swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refresh();
        }
    });
    theme1 = theme;
    if (theme == 2) {
        if (hour <= 6 || hour >= 18) {
            theme1 = 1;
        } else
            theme1 = 0;
    }
    if (theme1 == 1) {
        getActivity().getWindow().getDecorView().setBackgroundColor(Color.BLACK);
        listview.setBackgroundColor(Color.BLACK);
    }
    m = (MainActivity) getActivity();
    m.supportInvalidateOptionsMenu();
    Animation animation1 = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_newtab);
    FloatingActionButton floatingActionButton = (FloatingActionButton) rootView.findViewById(R.id.fab);
    floatingActionButton.show(true);
    floatingActionButton.setColorNormal(Color.parseColor(((MainActivity) getActivity()).skin));
    floatingActionButton.setColorPressed(Color.parseColor(((MainActivity) getActivity()).skin));

    floatingActionButton.setAnimation(animation1);
    //getActivity().findViewById(R.id.fab).setVisibility(View.VISIBLE);
    listview.setHasFixedSize(true);
    getActivity().findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final MaterialDialog.Builder ba1 = new MaterialDialog.Builder(getActivity());
            ba1.title(utils.getString(getActivity(), R.string.addbook));
            View v = getActivity().getLayoutInflater().inflate(R.layout.dialog, null);
            final EditText edir = (EditText) v.findViewById(R.id.newname);
            edir.setHint(utils.getString(getActivity(), R.string.enterpath));
            ba1.customView(v, true);
            if (theme1 == 1)
                ba1.theme(Theme.DARK);
            ba1.negativeText(R.string.cancel);
            ba1.positiveText(R.string.create);
            String skin = Sp.getString("skin_color", "#03A9F4");
            ba1.positiveColor(Color.parseColor(skin));
            ba1.negativeColor(Color.parseColor(skin));
            ba1.callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog materialDialog) {
                    try {
                        File a = new File(edir.getText().toString());
                        if (a.isDirectory()) {
                            s.addS(a);
                            b.items.add(a);
                            b.notifyDataSetChanged();
                            Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.success),
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.invalid_dir),
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getActivity(), utils.getString(getActivity(), R.string.error),
                                Toast.LENGTH_LONG).show();
                    }
                    m.updateDrawer();
                }

                @Override
                public void onNegative(MaterialDialog materialDialog) {

                }
            });
            ba1.build().show();

        }
    });

    icons = new IconUtils(Sp, getActivity());
    if (savedInstanceState == null)
        refresh();
    else {
        bx = utils.toFileArray(savedInstanceState.getStringArrayList("bx"));
        refresh(bx);
        linearLayoutManager.scrollToPositionWithOffset(savedInstanceState.getInt("index"),
                savedInstanceState.getInt("top"));
    }

}

From source file:com.tenforwardconsulting.cordova.bgloc.AbstractLocationService.java

private Integer parseNotificationIconColor(String color) {
    int iconColor = 0;
    if (color != null) {
        try {//  w  w w.  j  a va  2 s.  c om
            iconColor = Color.parseColor(color);
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "couldn't parse color from android options");
        }
    }
    return iconColor;
}

From source file:com.brodev.socialapp.view.ImagePagerActivity.java

/**
 * Change color/*from  w  w w . java  2 s. com*/
 * @param colorCode
 */
private void changeColor(String colorCode) {
    if ("Brown".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#da6e00"));
        comment.setTextColor(Color.parseColor("#da6e00"));
        total_like.setTextColor(Color.parseColor("#da6e00"));
        total_comment.setTextColor(Color.parseColor("#da6e00"));
        like_icon.setImageResource(R.drawable.brown_like_icon);
        comment_icon.setImageResource(R.drawable.brown_commet_icon);
    } else if ("Pink".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#ef4964"));
        comment.setTextColor(Color.parseColor("#ef4964"));
        total_like.setTextColor(Color.parseColor("#ef4964"));
        total_comment.setTextColor(Color.parseColor("#ef4964"));
        like_icon.setImageResource(R.drawable.pink_like_icon);
        comment_icon.setImageResource(R.drawable.pink_commet_icon);
    } else if ("Green".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#3a8d01"));
        comment.setTextColor(Color.parseColor("#3a8d01"));
        total_like.setTextColor(Color.parseColor("#3a8d01"));
        total_comment.setTextColor(Color.parseColor("#3a8d01"));
        like_icon.setImageResource(R.drawable.green_like_icon);
        comment_icon.setImageResource(R.drawable.green_commet_icon);
    } else if ("Violet".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#8190db"));
        comment.setTextColor(Color.parseColor("#8190db"));
        total_like.setTextColor(Color.parseColor("#8190db"));
        total_comment.setTextColor(Color.parseColor("#8190db"));
        like_icon.setImageResource(R.drawable.violet_like_icon);
        comment_icon.setImageResource(R.drawable.violet_commet_icon);
    } else if ("Red".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#ff0606"));
        comment.setTextColor(Color.parseColor("#ff0606"));
        total_like.setTextColor(Color.parseColor("#ff0606"));
        total_comment.setTextColor(Color.parseColor("#ff0606"));
        like_icon.setImageResource(R.drawable.red_like_icon);
        comment_icon.setImageResource(R.drawable.red_commet_icon);
    } else if ("Dark Violet".equalsIgnoreCase(colorCode)) {
        like.setTextColor(Color.parseColor("#4e529b"));
        comment.setTextColor(Color.parseColor("#4e529b"));
        total_like.setTextColor(Color.parseColor("#4e529b"));
        total_comment.setTextColor(Color.parseColor("#4e529b"));
        like_icon.setImageResource(R.drawable.dark_violet_like_icon);
        comment_icon.setImageResource(R.drawable.dark_violet_commet_icon);
    } else {
        like.setTextColor(Color.parseColor("#0084c9"));
        comment.setTextColor(Color.parseColor("#0084c9"));
        total_like.setTextColor(Color.parseColor("#0084c9"));
        total_comment.setTextColor(Color.parseColor("#0084c9"));
        like_icon.setImageResource(R.drawable.like_icon);
        comment_icon.setImageResource(R.drawable.commet_icon);
    }
}

From source file:ch.timjahn.learningapp.ls.java

public void control(View view) {
    int progress = ((SeekBar) findViewById(R.id.seekBar)).getProgress();
    TextView tv = (TextView) findViewById(R.id.solution);
    tv.setVisibility(View.VISIBLE);
    switch (activeQ) {
    case 1://  w  ww  .  j a v a2  s. c o  m
        if (activeA.equals(answer1)) {
            tv.setText("Richtig (~90|100).");
            tv.setTextColor(Color.parseColor("#00CC00"));
        } else {
            tv.setText("Falsch.");
            tv.setTextColor(Color.RED);
        }
        break;
    case 2:
        if (activeA.equals(answer2)) {
            tv.setText("Richtig (~45|100)");
            tv.setTextColor(Color.parseColor("#00CC00"));
        } else {
            tv.setText("Falsch.");
            tv.setTextColor(Color.RED);
        }
        break;
    }
}

From source file:com.echo.holographlibrarysample.BarFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View v = inflater.inflate(R.layout.fragment_bargraph, container, false);
    final Resources resources = getResources();
    ArrayList<Bar> aBars = new ArrayList<Bar>();
    Bar bar = new Bar();
    bar.setColor(resources.getColor(R.color.green_light));
    bar.setSelectedColor(resources.getColor(R.color.transparent_orange));
    bar.setName("Test1");
    bar.setValue(1000);// w  w w .ja  va2 s.  c o m
    bar.setValueString("$1,000");
    aBars.add(bar);
    bar = new Bar();
    bar.setColor(resources.getColor(R.color.orange));
    bar.setName("Test2");
    bar.setValue(2000);
    bar.setValueString("$2,000");
    aBars.add(bar);
    bar = new Bar();
    bar.setColor(resources.getColor(R.color.purple));
    bar.setName("Test3");
    bar.setValue(1500);
    bar.setValueString("$1,500");
    aBars.add(bar);

    final BarGraph barGraph = (BarGraph) v.findViewById(R.id.bargraph);
    bg = barGraph;
    barGraph.setBars(aBars);

    barGraph.setOnBarClickedListener(new OnBarClickedListener() {

        @Override
        public void onClick(int index) {
            Toast.makeText(getActivity(),
                    "Bar " + index + " clicked " + String.valueOf(barGraph.getBars().get(index).getValue()),
                    Toast.LENGTH_SHORT).show();
        }
    });
    Button animateBarButton = (Button) v.findViewById(R.id.animateBarButton);
    Button animateInsertBarButton = (Button) v.findViewById(R.id.animateInsertBarButton);
    Button animateDelteBarButton = (Button) v.findViewById(R.id.animateDeleteBarButton);

    //animate to random values
    animateBarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (Bar b : barGraph.getBars()) {
                b.setGoalValue((float) Math.random() * 1000);
                b.setValuePrefix("$");//display the prefix throughout the animation
                Log.d("goal val", String.valueOf(b.getGoalValue()));
            }
            barGraph.setDuration(1200);//default if unspecified is 300 ms
            barGraph.setInterpolator(new AccelerateDecelerateInterpolator());//Only use over/undershoot  when not inserting/deleting
            barGraph.setAnimationListener(getAnimationListener());
            barGraph.animateToGoalValues();

        }
    });

    //insert a bar
    animateInsertBarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            barGraph.cancelAnimating(); //must clear existing to call onAnimationEndListener cleanup BEFORE adding new bars
            int newPosition = barGraph.getBars().size() == 0 ? 0
                    : new Random().nextInt(barGraph.getBars().size());
            Bar bar = new Bar();
            bar.setColor(Color.parseColor("#AA0000FF"));
            bar.setName("Insert bar " + String.valueOf(barGraph.getBars().size()));
            bar.setValue(0);
            bar.mAnimateSpecial = HoloGraphAnimate.ANIMATE_INSERT;
            barGraph.getBars().add(newPosition, bar);
            for (Bar b : barGraph.getBars()) {
                b.setGoalValue((float) Math.random() * 1000);
                b.setValuePrefix("$");//display the prefix throughout the animation
                Log.d("goal val", String.valueOf(b.getGoalValue()));
            }
            barGraph.setDuration(1200);//default if unspecified is 300 ms
            barGraph.setInterpolator(new AccelerateDecelerateInterpolator());//Don't use over/undershoot interpolator for insert/delete
            barGraph.setAnimationListener(getAnimationListener());
            barGraph.animateToGoalValues();

        }
    });

    //delete a bar
    animateDelteBarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            barGraph.cancelAnimating(); //must clear existing to call onAnimationEndListener cleanup BEFORE adding new bars
            if (barGraph.getBars().size() == 0)
                return;

            for (Bar b : barGraph.getBars()) {
                b.setGoalValue((float) Math.random() * 1000);
                b.setValuePrefix("$");//display the prefix throughout the animation
                Log.d("goal val", String.valueOf(b.getGoalValue()));
            }
            int newPosition = new Random().nextInt(barGraph.getBars().size());
            Bar bar = barGraph.getBars().get(newPosition);
            bar.mAnimateSpecial = HoloGraphAnimate.ANIMATE_DELETE;
            bar.setGoalValue(0);//animate to 0 then delete
            barGraph.setDuration(1200);//default if unspecified is 300 ms
            barGraph.setInterpolator(new AccelerateInterpolator());//Don't use over/undershoot interpolator for insert/delete
            barGraph.setAnimationListener(getAnimationListener());
            barGraph.animateToGoalValues();

        }
    });
    return v;
}

From source file:com.eugene.fithealthmaingit.UI.MealView.MealViewActivity.java

private void InitializePagerTabs() {
    mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
        @Override/*from  w  w w  .j  a  va2 s. c o m*/
        public Fragment getItem(int position) {
            LogMeal log = mLogMealAdapter.getItem(position);
            return MealViewFragment.newInstance(log.getId());
        }

        @Override
        public CharSequence getPageTitle(int position) { // Tab text
            LogMeal logMeal1 = mLogMealAdapter.getItem(position);
            String s;
            if (logMeal1.getMealName().toString().trim().length() > 12) {
                s = logMeal1.getMealName().substring(0, 12) + "..";
            } else {
                s = logMeal1.getMealName();
            }
            return s;
        }

        @Override
        public int getCount() {
            return mLogMealAdapter.getCount();
        }
    });

    tabs.setTabTextColors(Color.parseColor("#80ffffff"), Color.parseColor("#ffffff"));
    if (mLogMealAdapter.getCount() == 1) {
        tabs.setTabMode(TabLayout.MODE_FIXED);
    } else {
        tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
    }
}

From source file:com.example.sam.savemeapp.StatisticsFragment.java

/**
 * Sets up the entries of the pie chart and colors associated with this entries.
 * After doing so this information will be added to a DataSet which contains information for the pie chart.
 * The if statements is used to avoid having empty entries show
 * up in the pie chart, they would be stacked un top of each other.
 *//*from   ww  w  . java 2 s .  com*/
public void setData() {
    if (u.categories.get("Food & Beverage").get("Food & Beverage") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Food & Beverage").get("Food & Beverage"), "Food & Beverage",
                ContextCompat.getDrawable(getContext(), R.drawable.food_bev_icon),
                Color.parseColor("#00a0ae")));
        colors.add(Color.parseColor("#49d7e8"));
    }
    if (u.categories.get("Transportation").get("Transportation") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Transportation").get("Transportation"), "Transportation",
                ContextCompat.getDrawable(getContext(), R.drawable.transp_icon), Color.parseColor("#be3127")));
        colors.add(Color.parseColor("#eb6056"));
    }
    if (u.categories.get("Shopping").get("Shopping") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Shopping").get("Shopping"), "Shopping",
                ContextCompat.getDrawable(getContext(), R.drawable.shopping_icon),
                Color.parseColor("#7dc725")));
        colors.add(Color.parseColor("#89dc27"));
    }
    if (u.categories.get("Entertainment").get("Entertainment") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Entertainment").get("Entertainment"), "Entertainment",
                ContextCompat.getDrawable(getContext(), R.drawable.entertainment_icon),
                Color.parseColor("#e88300")));
        colors.add(Color.parseColor("#f7a234"));
    }
    if (u.categories.get("Health").get("Health") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Health").get("Health"), "Health",
                ContextCompat.getDrawable(getContext(), R.drawable.health_icon), Color.parseColor("#dc006d")));
        colors.add(Color.parseColor("#f4507a"));
    }
    if (u.categories.get("Bills").get("Bills") < 0) {
        yvalues.add(new PieEntry(-u.categories.get("Bills").get("Bills"), "Bills",
                ContextCompat.getDrawable(getContext(), R.drawable.bills_icon), Color.parseColor("#1562a4")));
        colors.add(Color.parseColor("#3599ef"));
    }
    //This if statement secures that our "no data available" is shown.
    if (yvalues.size() != 0) {
        dataSet = new PieDataSet(yvalues, "");
        dataSet.setColors(colors);
        data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        pieChart.setData(data);
        setUpPiechart();
    }
}

From source file:com.fa.mastodon.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("light")) {
        View view = this.getWindow().getDecorView();
        view.setBackgroundColor(Color.parseColor("#EEEEEE"));
    } else if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("black")) {
        View view = this.getWindow().getDecorView();
        view.setBackgroundColor(Color.parseColor("#000000"));
    }/* w ww . ja v  a  2s.  c o  m*/
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pageHistory = new Stack<>();
    if (savedInstanceState != null) {
        List<Integer> restoredHistory = savedInstanceState.getIntegerArrayList("pageHistory");
        if (restoredHistory != null) {
            pageHistory.addAll(restoredHistory);
        }
    }

    ButterKnife.bind(this);

    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSheetLayout.expandFab();
        }
    });

    TypedArray array = getTheme().obtainStyledAttributes(new int[] { android.R.attr.colorBackground, });
    int backgroundColor = array.getColor(0, 0xFF00FF);
    array.recycle();

    mSheetLayout.setFab(floatingBtn);
    mSheetLayout.setFabAnimationEndListener(this);
    mSheetLayout.setColor(backgroundColor);

    setupDrawer();
    setupSearchView();

    /* Fetch user info while we're doing other things. This has to be after setting up the
     * drawer, though, because its callback touches the header in the drawer. */
    fetchUserInfo();

    // Setup the tabs and timeline pager.
    TimelinePagerAdapter adapter = new TimelinePagerAdapter(getSupportFragmentManager());

    int pageMargin = getResources().getDimensionPixelSize(R.dimen.tab_page_margin);
    viewPager.setPageMargin(pageMargin);
    Drawable pageMarginDrawable = ThemeUtils.getDrawable(this, R.attr.tab_page_margin_drawable,
            R.drawable.tab_page_margin_dark);
    viewPager.setPageMarginDrawable(pageMarginDrawable);
    viewPager.setAdapter(adapter);

    int[] tabIcons = { R.drawable.ic_home_24dp, R.drawable.ic_notifications_24dp, R.drawable.ic_local_24dp,
            R.drawable.ic_public_24dp, };
    String[] pageTitles = { getString(R.string.title_home), getString(R.string.title_notifications),
            getString(R.string.title_public_local), getString(R.string.title_public_federated), };

    Intent intent = getIntent();

    bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);

    AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.app_name,
            R.drawable.ic_timeline_black_36dp, R.color.colorPrimaryDark);
    AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.app_name,
            R.drawable.ic_notifications_24dp, R.color.colorPrimaryDark);
    AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.app_name, R.drawable.ic_face_black_36dp,
            R.color.colorPrimaryDark);
    AHBottomNavigationItem item4 = new AHBottomNavigationItem(R.string.app_name,
            R.drawable.ic_language_black_36dp, R.color.colorPrimaryDark);

    bottomNavigation.addItem(item1);
    bottomNavigation.addItem(item2);
    bottomNavigation.addItem(item3);
    bottomNavigation.addItem(item4);

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("light")) {
        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#FFFFFF"));
        bottomNavigation.setInactiveColor(Color.parseColor("#727272"));
    } else if (PreferenceManager.getDefaultSharedPreferences(this).getString("theme_selection", "light")
            .equals("black")) {
        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#000000"));
        bottomNavigation.setInactiveColor(Color.parseColor("#DDDDDD"));
    } else {
        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#363c4b"));
        bottomNavigation.setInactiveColor(Color.parseColor("#68738f"));
    }

    bottomNavigation.setBehaviorTranslationEnabled(false);

    bottomNavigation.setAccentColor(Color.parseColor("#2b90d9"));

    bottomNavigation.setForceTint(true);

    bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_HIDE);

    bottomNavigation.setColored(false);
    bottomNavigation.setUseElevation(true);

    bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
        @Override
        public boolean onTabSelected(int position, boolean wasSelected) {
            viewPager.setCurrentItem(position);

            if (pageHistory.isEmpty()) {
                pageHistory.push(0);
            }

            if (pageHistory.contains(position)) {
                pageHistory.remove(pageHistory.indexOf(position));
            }

            pageHistory.push(position);
            return true;
        }
    });

    bottomNavigation.setCurrentItem(0);

    int tabSelected = 0;
    if (intent != null) {
        int tabPosition = intent.getIntExtra("tab_position", 0);
        if (tabPosition != 0) {
            if (bottomNavigation.getItem(tabPosition) != null) {
                bottomNavigation.setCurrentItem(tabPosition);
            }
        }
    }

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            bottomNavigation.setCurrentItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    // Setup push notifications
    if (arePushNotificationsEnabled()) {
        enablePushNotifications();
    } else {
        disablePushNotifications();
    }

    composeButton = floatingBtn;

    if (!DonateActivity.isPlus(this)) {
        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(this, "ca-app-pub-8245120186869512~8307608980");

        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-8245120186869512/2261075384");

        requestNewInterstitial();

        mInterstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                mInterstitialAd.show();
            }
        });
    }
}

From source file:de.incoherent.suseconferenceclient.app.ConferenceCacher.java

public long cacheConference(Conference conference, Database db) {

    //String url = conference.getUrl();
    String url = "https://conference.opensuse.org/osem/api/v1/conferences/gRNyOIsTbvCfJY5ENYovBA";
    String eventsUrl = url + "/events.json";
    String roomsUrl = url + "/rooms.json";
    String speakersUrl = url + "/speakers.json";
    String tracksUrl = url + "/tracks.json";
    String venueUrl = url + "/venue.json";
    Long returnVal = null;// w w w  .j ava  2  s .com
    HashMap<String, Long> roomMap = new HashMap<String, Long>();
    HashMap<String, Long> trackMap = new HashMap<String, Long>();
    HashMap<String, Long> speakerMap = new HashMap<String, Long>();

    try {
        Log.d("SUSEConferences", "Venues: " + venueUrl);
        publishProgress("venues");
        JSONObject venueReply = HTTPWrapper.get(venueUrl);
        JSONObject venue = venueReply.getJSONObject("venue");
        String infoUrl = url + "/" + venue.getString("info_text");
        Log.d("Application Url", "INFO URL: " + infoUrl);
        String info = HTTPWrapper.getRawText(infoUrl);
        String venueName = venue.getString("name");
        String venueAddr = venue.getString("address");
        String offlineMap = "";
        String offlineMapBounds = "";
        if (venue.has("offline_map")) {
            offlineMap = venue.getString("offline_map");
            offlineMapBounds = venue.getString("offline_map_bounds");
        }

        long venueId = db.insertVenue(venue.getString("guid"), venueName, venueAddr, offlineMap,
                offlineMapBounds, info);
        JSONArray mapPoints = venue.getJSONArray("map_points");
        int mapLen = mapPoints.length();
        for (int i = 0; i < mapLen; i++) {
            JSONObject point = mapPoints.getJSONObject(i);
            String lat = point.getString("lat");
            String lon = point.getString("lon");
            String type = point.getString("type");
            String name = "Unknown Point";
            String addr = "Unknown Address";
            String desc = "";

            if (point.has("name")) {
                name = point.getString("name");
            }
            if (point.has("address")) {
                addr = point.getString("address");
            }
            if (point.has("description")) {
                desc = point.getString("description");
            }

            db.insertVenuePoint(venueId, lat, lon, type, name, addr, desc);
        }

        if (venue.has("map_polygons")) {
            JSONArray polygons = venue.getJSONArray("map_polygons");
            int polygonLen = polygons.length();
            for (int j = 0; j < polygonLen; j++) {
                JSONObject polygon = polygons.getJSONObject(j);
                String name = polygon.getString("name");
                String label = polygon.getString("label");
                String lineColorStr = polygon.getString("line_color");
                String fillColorStr = "#00000000";
                if (polygon.has("fill_color"))
                    fillColorStr = polygon.getString("fill_color");

                List<String> stringList = new ArrayList<String>();
                JSONArray points = polygon.getJSONArray("points");
                int pointsLen = points.length();
                for (int k = 0; k < pointsLen; k++) {
                    String newPoint = points.getString(k);
                    stringList.add(newPoint);
                }
                String joined = TextUtils.join(";", stringList);
                int lineColor = Color.parseColor(lineColorStr);
                int fillColor = Color.parseColor(fillColorStr);
                db.insertVenuePolygon(venueId, name, label, lineColor, fillColor, joined);
            }
        }

        db.setConferenceVenue(venueId, conference.getSqlId());

        Log.d("SUSEConferences", "Rooms");
        publishProgress("rooms");
        JSONObject roomsReply = HTTPWrapper.get(roomsUrl);
        Log.d("Rooms of the event", "ROOMS URL: " + roomsUrl);
        JSONArray rooms = roomsReply.getJSONArray("rooms");
        int roomsLen = rooms.length();
        for (int i = 0; i < roomsLen; i++) {
            JSONObject room = rooms.getJSONObject(i);
            String guid = room.getString("guid");
            Long roomId = db.insertRoom(guid, room.getString("name"), room.getString("description"), venueId);
            roomMap.put(guid, roomId);
        }
        Log.d("SUSEConferences", "Tracks");
        publishProgress("tracks");
        JSONObject tracksReply = HTTPWrapper.get(tracksUrl);
        Log.d("Event tracks", "Tracks: " + tracksUrl);
        JSONArray tracks = tracksReply.getJSONArray("tracks");
        int tracksLen = tracks.length();
        for (int i = 0; i < tracksLen; i++) {
            JSONObject track = tracks.getJSONObject(i);
            String guid = track.getString("guid");
            Long trackId = db.insertTrack(guid, track.getString("name"), track.getString("color"),
                    conference.getSqlId());
            trackMap.put(guid, trackId);
        }
        Log.d("SUSEConferences", "Speakers");
        publishProgress("speakers");
        JSONObject speakersReply = HTTPWrapper.get(speakersUrl);
        JSONArray speakers = speakersReply.getJSONArray("speakers");
        int speakersLen = speakers.length();
        for (int i = 0; i < speakersLen; i++) {
            JSONObject speaker = speakers.getJSONObject(i);
            String guid = speaker.getString("guid");
            Long speakerId = db.insertSpeaker(guid, speaker.getString("name"), speaker.getString("company"),
                    speaker.getString("biography"), "");
            speakerMap.put(guid, speakerId);

        }

        Log.d("SUSEConferences", "Events");
        publishProgress("events");
        JSONObject eventsReply = HTTPWrapper.get(eventsUrl);
        JSONArray events = eventsReply.getJSONArray("events");
        int eventsLen = events.length();
        for (int i = 0; i < eventsLen; i++) {
            JSONObject event = events.getJSONObject(i);
            String guid = event.getString("guid");
            String track = event.getString("track");
            Long trackId = trackMap.get(track);
            Long roomId = roomMap.get(event.getString("room"));
            if (track.equals("meta")) {
                // The "meta" track is used to insert information
                // into the schedule that automatically appears on "my schedule",
                // and also isn't clickable.
                db.insertEvent(guid, conference.getSqlId(), roomId.longValue(), trackId.longValue(),
                        event.getString("date"), event.getInt("length"), "", "", event.getString("title"), "",
                        "");
            } else {
                Long eventId = db.insertEvent(guid, conference.getSqlId(), roomId.longValue(),
                        trackId.longValue(), event.getString("date"), event.getInt("length"),
                        event.getString("type"), event.getString("language"), event.getString("title"),
                        event.getString("abstract"), "");

                JSONArray eventSpeakers = event.getJSONArray("speaker_ids");
                int eventSpeakersLen = eventSpeakers.length();
                for (int j = 0; j < eventSpeakersLen; j++) {
                    Long speakerId = speakerMap.get(eventSpeakers.getString(j));
                    if (speakerId != null)
                        db.insertEventSpeaker(speakerId, eventId);
                }
            }
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        mErrorMessage = e.getLocalizedMessage();
        returnVal = Long.valueOf(-1);
    } catch (SocketException e) {
        e.printStackTrace();
        mErrorMessage = e.getLocalizedMessage();
        returnVal = Long.valueOf(-1);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        mErrorMessage = e.getLocalizedMessage();
        returnVal = Long.valueOf(-1);
    } catch (IOException e) {
        e.printStackTrace();
        mErrorMessage = e.getLocalizedMessage();
        returnVal = Long.valueOf(-1);
    } catch (JSONException e) {
        e.printStackTrace();
        mErrorMessage = e.getLocalizedMessage();
        returnVal = Long.valueOf(-1);
    }

    if (returnVal == null)
        returnVal = conference.getSqlId();
    return returnVal;
}

From source file:com.phonegap.bossbolo.plugin.statusbar.StatusBar.java

private void setStatusBarBackgroundColor(final String colorPref) {
    if (Build.VERSION.SDK_INT >= 21) {
        if (colorPref != null && !colorPref.isEmpty()) {
            final Window window = cordova.getActivity().getWindow();
            // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK
            window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            try {
                // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21
                window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window,
                        Color.parseColor(colorPref));
            } catch (IllegalArgumentException ignore) {
                Log.e(TAG, "Invalid hexString argument, use f.i. '#999999'");
            } catch (Exception ignore) {
                // this should not happen, only in case Android removes this method in a version > 21
                Log.w(TAG, "Method window.setStatusBarColor not found for SDK level " + Build.VERSION.SDK_INT);
            }//from w  w w. ja v  a  2  s.  c om
        }
    }
}