HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Data formatting using string spanning

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formattingstringusingdataspanning

Problem

I would like to know how to make my code better. I'm still a newbie in Android, so any tips are appreciated.

The code is an AsyncTask class extender that formats data into a nice looking Spannable String. It works, but it's quite slow, even if ran on a background thread.

```
//SlideContentType is an enumerable with 4 options: Movie, Action, Game, Music
//SlideContent is a class that stores info about a specific movie/song/game etc...
public class PickCardAsyncTask extends AsyncTask>, Integer, Pair> {

@Override
protected Pair doInBackground(Pair>... pairs){

//Get a reference to the list of all Slide Contents containing movies/games/etc.
List list = (List) pairs[0].second;

//Select a random item in the list
Random random = new Random();
random.setSeed(System.nanoTime());
int randomNr = random.nextInt(list.size());
SlideContent currentContent = list.get(randomNr);

//The link and the content are released as a pair
String websiteLink = currentContent.movieWebsite;

//End result variable
SpannableStringBuilder coloredString = new SpannableStringBuilder();

//Do the appropriate actions
if(pairs[0].first == SlideContent.SlideContentType.Movie){

//Format the information from the Slide Content into a nice looking Spannable String
SpannableString text = new SpannableString(currentContent.movieTitle);
text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
coloredString.append(text);

coloredString.append(" (" + currentContent.movieYear + ")\n");

text = new SpannableString(currentContent.movieGenres);
text.setSpan(new RelativeSizeSpan(0.7f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
coloredString.

Solution

Random random = new Random();
random.setSeed(System.nanoTime());


Don't put this inside here. I'm assuming that this method will end up being called more than once. If so, you don't want to be seeding and re-seeding the Random every call.

random should be moved to a field of the class. Also, I don't think you need to manually call Random.setSeed. See here for more details.

I don't know my Java 100%, but I think this might be a typo:

Pair>... pairs


I think it should be:

Pair, List... pairs

Code Snippets

Random random = new Random();
random.setSeed(System.nanoTime());
Pair<SlideContent.SlideContentType, List<SlideContent>>... pairs
Pair<SlideContent.SlideContentType>, List<SlideContent>... pairs

Context

StackExchange Code Review Q#93528, answer score: 2

Revisions (0)

No revisions yet.