How to display a different toast message on multiple instances of SpannableString? - java

I am getting data from a json file and I want to have a different toast (on click) for each spannable string on the textview.
It works but it only shows the same toast message for each spannablestring on the textview; specifically its only showing the very last currentLocation on the json file.
for(int k = 0; k < 8;k++) {
spannableString1 = new SpannableString("Destination: " + canningTownArrivals1.get(k).destinationName); //spannable string is in the scope of the for loop,
ClickableSpan clickableSpan1 = new ClickableSpan() {
#Override
public void onClick(View view1) {
for(int c = 0; c < 8; c++){
Toast.makeText(CanningTownActivity.this,canningTownArrivals1.get(c).currentLocation,Toast.LENGTH_LONG)
.show();
}
}
};
spannableString1.setSpan(clickableSpan1,0,canningTownArrivals1.get(k).length() + 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textViewResult1.append(spannableString1);
textViewResult1.append(
"\nTime: " + canningTownArrivals1.get(k).timeToStation + " mins\n");
textViewResult1.setMovementMethod(LinkMovementMethod.getInstance());
}
I want it to show a different currentLocation on each spannableString.

for(int k = 0; k < 8;k++) {
spannableString1 = new SpannableString("Destination: " + canningTownArrivals1.get(k).destinationName); //spannable string is in the scope of the for loop,
spannableString1.setSpan(createClickableSpan(canningTownArrivals1.get(k).currentLocation),0,canningTownArrivals1.get(k).length() + 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textViewResult1.append(spannableString1);
textViewResult1.append(
"\nTime: " + canningTownArrivals1.get(k).timeToStation + " mins\n");
textViewResult1.setMovementMethod(LinkMovementMethod.getInstance());
}
private ClickableSpan createClickableSpan(final String location) {
return new ClickableSpan() {
#Override
public void onClick(#NonNull View widget) {
Toast.makeText(CanningTownActivity.this,location,Toast.LENGTH_LONG)
.show();
}
};
}

Related

Play sequence of animations on one view from onAnimationEnd

I'm trying to play a sequence of more than 1 animations on the same progress bar. I am actually using a library called AnimateHorizontalProgressBar which allows the progress bars to fill up with an animation. The bar is an experience bar in a game, and if the player gets enough experience at one time, I want the bar to fill up as many times as there are level ups. (e.g. a level 1 character going to level 3 would have their experience bar fill up 2 full times, resetting whenever it gets full, then once more for however much progress they made from level 3 to level 4)
The solution I tried was to set an AnimateProgressListener on the AnimateHorizontalProgressBar, and in the onAnimationEnd function, to call the next animation to be played. The list containing these animations is an arraylist of custom POJOs which hold a reference to the view (the progress bar), and the percent to set it to.
public class MonsterBattleResolutionFragment extends MMOBaseFragment {
private static final String TAG = "Resolution Frag";
boolean isVictorious;
boolean playerCapturedMonster;
private String wildMonsterId;
ToolTipManager tooltips;
int monsterLevel;
private FirebaseFunctions mFunctions;
private ArrayList<String> monsterKeys;
private ArrayList<PlayerMonster> monstersList;
private BattleResolutionXpGainedAdapter battleResolutionXpGainedAdapter;
private Typeface typeface;
TextView victoryTextView;
private ListView xpGainedLayoutContainer;
private RecyclerView itemRecyclerView;
private PlayerItemAdapter playerItemAdapter;
ArrayList<PlayerItem> playerItems;
private FirebaseUser user;
private DatabaseReference mDatabase;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_monster_battle_resolution, container, false);
mFunctions = FirebaseFunctions.getInstance();
typeface = CustomTypeFace.getNovemberTypeface(getContext());
victoryTextView = view.findViewById(R.id.monster_battle_resolution_text_view);
victoryTextView.setTypeface(typeface);
tooltips = new ToolTipManager(getActivity());
itemRecyclerView = view.findViewById(R.id.monster_battle_resolution_item_recycler_view);
itemRecyclerView.setNestedScrollingEnabled(false);
itemRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
playerItems = new ArrayList<>();
playerItemAdapter = new PlayerItemAdapter(playerItems);
itemRecyclerView.setAdapter(playerItemAdapter);
isVictorious = getArguments().getBoolean("victory");
playerCapturedMonster = getArguments().getBoolean("playerCapturedMonster");
monsterLevel = getArguments().getInt("monsterLevel");
monsterKeys = getArguments().getStringArrayList("monsterKeys");
monstersList = getArguments().getParcelableArrayList("monstersList");
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, monstersList.get(i).getMonsterStringName());
}
wildMonsterId = getArguments().getString("wildMonsterId");
ArrayList<String> playerMonsterIds = new ArrayList<>();
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, "fb id is " + monstersList.get(i).getFirebaseId());
playerMonsterIds.add(monstersList.get(i).getFirebaseId());
}
Task<HashMap<String, Integer>> test = firebaseResolveCombat(wildMonsterId, playerMonsterIds);
test.addOnCompleteListener(new OnCompleteListener<HashMap<String, Integer>>() {
#Override
public void onComplete(#NonNull Task<HashMap<String, Integer>> task) {
Object gainedXp = task.getResult().get("experience");
Object items = task.getResult().get("items");
Object skills = task.getResult().get("skills");
Object newMonsterLevels = task.getResult().get("newMonsterLevels");
// gainedXp is the xp gained for each monster involved in the fight
if (gainedXp != null){
Log.e(TAG, "experience earned: " + gainedXp);
updateXpBars((int) gainedXp);
}
if (items != null){
Log.e(TAG, "items earned: " + items.toString());
HashMap<String, Integer> itemsEarnedMap = (HashMap<String, Integer>) items;
for (Map.Entry<String, Integer> item : itemsEarnedMap.entrySet()) {
Log.e(TAG, "key: " + item.getKey() + ", value: " + item.getValue());
// add new item to list for adapter. NOTE: as of now, key is a string, while value (quantity) is an int. slight issue on javascript side, fine for now.
playerItems.add(ItemDirectory.itemLookup(Integer.parseInt(item.getKey()), item.getValue()));
}
}
if (skills != null){
Log.e(TAG, "new skills: " + skills.toString());
HashMap<String, ArrayList<Integer>> newSkills = (HashMap<String, ArrayList<Integer>>) skills;
for (Map.Entry<String, ArrayList<Integer>> item : newSkills.entrySet()) {
for (Integer skill : item.getValue()) {
String skillName = SkillDirectory.skillLookup(skill).getName();
Log.e(TAG, item.getKey() + " learned skill " + skillName);
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, "fb id is " + monstersList.get(i).getFirebaseId());
if (monstersList.get(i).getFirebaseId().equals(item.getKey())){
Toast.makeText(getContext(), monstersList.get(i).getMonsterStringName() + " learned skill " + skillName + "!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
if (newMonsterLevels != null){
Log.e(TAG, "new levels: " + newMonsterLevels.toString());
}
}
});
xpGainedLayoutContainer = view.findViewById(R.id.monster_battle_resolution_xp_gained_layout_container);
battleResolutionXpGainedAdapter = new BattleResolutionXpGainedAdapter(getActivity(), R.layout.battle_resolution_xp_gained_layout, monstersList);
xpGainedLayoutContainer.setAdapter(battleResolutionXpGainedAdapter);
justifyListViewHeightBasedOnChildren(xpGainedLayoutContainer);
// if the player did not win, don't show items won, give them half xp
if (!isVictorious) {
victoryTextView.setText(R.string.defeat);
}
// listener for button to return to map
FloatingActionButton b = view.findViewById(R.id.monster_battle_resolution_return_to_map_button);
b.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
});
return view;
}
private void updateXpBars(int xpPerMonster){
ArrayList<LevelUpBarAnimation> animationList = new ArrayList<>();
// First build the list of animations
Log.e(TAG, "There are " + battleResolutionXpGainedAdapter.getCount() + " xp bars to animate");
for (int i = 0; i < battleResolutionXpGainedAdapter.getCount(); i++){
int currentXp = monstersList.get(i).getExperience();
int level = monstersList.get(i).getLevel();
int newXp = currentXp + xpPerMonster;
int lastLevelXp = getExperienceRequiredForNextLevel(level-1);
boolean isLevelUp = false;
int xpNumerator = newXp - lastLevelXp;
int xpDenominator = getExperienceRequiredForNextLevel(level) - lastLevelXp;
Log.e(TAG, "Monster was level: " + level + ", and had " + currentXp + " xp");
Log.e(TAG, "now has " + newXp + " xp. level now: " + getLevelBasedOnExperience(newXp));
// In a loop, build up every animation which needs to be done on this particular xp bar. Loop is so multiple animations may be played for multiple level ups\
// do while because even when the monster does not level up, they still will get some xp so at least 1 anim needs to be played
do {
isLevelUp = false; // Need to reset to know when we have not leveled up
AnimateHorizontalProgressBar bar = xpGainedLayoutContainer.getChildAt(i).findViewById(R.id.battle_resolution_xp_gained_xp_bar);
bar.setMax(10000);
if (newXp > getExperienceRequiredForNextLevel(level)){
isLevelUp = true;
level++;
xpNumerator = xpDenominator; // Sets the xp bar to full before resetting at 0 for the next level
}
Log.e(TAG, "Added new anim for bar at position " + i + ", " + "out of 10000: " + (int) (((double) xpNumerator / (double) xpDenominator) * 10000.0));
// TODO: clean up messy cast
LevelUpBarAnimation levelUpBarAnimation = new LevelUpBarAnimation(bar, (int) (((double) xpNumerator / (double) xpDenominator) * 10000.0), level);
levelUpBarAnimation.setLevelUp(isLevelUp);
Log.e(TAG, "islevelup set to " + String.valueOf(levelUpBarAnimation.isLevelUp()) + ", going from level " + (level-1) + " to " + (level));
levelUpBarAnimation.setLevelTxtView(xpGainedLayoutContainer.getChildAt(i).findViewById(R.id.battle_resolution_xp_gained_level_text_view));
animationList.add(levelUpBarAnimation);
} while(isLevelUp);
}
final int[] animNumber = {0};
Log.e(TAG, "animlist size " + animationList.size() + " playing across " + battleResolutionXpGainedAdapter.getCount() + " xp bars");
for (int i = 0; i < battleResolutionXpGainedAdapter.getCount(); i++) {
AnimateHorizontalProgressBar bar = animationList.get(i).getXpBar();
bar.setAnimateProgressListener(new AnimateHorizontalProgressBar.AnimateProgressListener() {
#Override
public void onAnimationStart(int progress, int max) {
Log.e(TAG, "anim #" + animNumber[0] + " starting");
}
#Override
public void onAnimationEnd(int progress, int max) {
// If this xp bar filled up, play a flash sort of animation, and update the lvl text
if (animationList.get(animNumber[0]).isLevelUp()){
int newLvl = animationList.get(animNumber[0]).getLevel();
Log.e(TAG, "level up animation playing. anim number " + animNumber[0] + ", now level " + newLvl);
// Update the lvl txt
animationList.get(animNumber[0]).getLevelTxtView().setText("LVL: " + newLvl);
// Then set the progress on this bar back to 0
animationList.get(animNumber[0]).getXpBar().setProgress(0);
}
Log.e(TAG, "anim number " + animNumber[0] + " finished, next playing " + (animNumber[0] + 1));
// Do not attempt to play the next animation if this one was the last
if (animNumber[0] < animationList.size() - 1){
animNumber[0]++;
Log.e(TAG, "playing anim number " + animNumber[0] + " to " + animationList.get(animNumber[0]).getProgressPercent() + "% full");
animationList.get(animNumber[0]).getXpBar().setProgressWithAnim(animationList.get(animNumber[0]).getProgressPercent()); // TODO: this not getting called
}
}
});
}
Log.e(TAG, "playing anim number 0");
animationList.get(0).getXpBar().setProgressWithAnim(animationList.get(0).getProgressPercent());
}
// On receiving a new skill, this tooltip will appear momentarily to notify the player
public void showNewSkillTooltip(String skillName, View view) {
Log.e(TAG, "Showing new skill tooltip. skill learned: " + skillName);
// Dynamically build a layout here, as it cannot already have a parent layout if we want to assign it to the tooltip
LinearLayout tooltipLayout = new LinearLayout(getContext());
tooltipLayout.setOrientation(LinearLayout.VERTICAL);
TextView talentTitleText = new TextView(getContext());
talentTitleText.setTextSize(18f);
talentTitleText.setText(skillName);
tooltipLayout.addView(talentTitleText);
ToolTip toolTip = new ToolTip()
.withColor(getResources().getColor(R.color.grey_300)) //or whatever you want
.withAnimationType(ToolTip.AnimationType.FROM_MASTER_VIEW)
.withContentView(tooltipLayout)
.withShadow();
tooltips.showToolTip(toolTip, view);
}
private Task<HashMap<String, Integer>> firebaseResolveCombat(String wildMonsterFirebaseId, ArrayList<String> playerMonsterIds) {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("wildMonsterId", wildMonsterFirebaseId);
data.put("playerMonsterIds", playerMonsterIds);
return mFunctions
.getHttpsCallable("resolveWildMonsterCombat")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, HashMap<String, Integer>>() {
#Override
public HashMap then(#NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
HashMap<String, Integer> result = (HashMap<String, Integer>) task.getResult().getData();
return result;
}
});
}
}
I added the whole class. Forgive the messy code.
The problem is that after the first animation which I start explicitly, it runs the onAnimationEnd function, and hits the line to run the next animation, but it never starts. The onAnimationStart function is never even called for the 2nd animation. Any ideas on why this might be?
I'll also add this takes place in a dialog fragment. Not sure if that is relevant however.

sharedpreferences stringset value: How to remove in Android Studio.?

I have unchecked the checkbox(per item) to remove it . I am using to sharedpreferences with HashSet concept. I want to pass arraylist value from one page to another page. What i do what is my mistake some one help me.
My code is:
adapterpage.java
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
// editor.putString("key_name",itemId );
// editor.apply();
// }
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
// set.remove(addmembers);
addmembers.remove(k);
edit.remove(addmembers.get(k));
edit.commit();
break;
}
}
You are making mistake here ...
for (j = 0; j < addmembers.size(); j++) {
//set.addAll(addmembers);this will add every time whole data of list into set
set.add(addmembers.get(j));
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
And also here while removing change to this...
edit.remove("yourKey");
Try this code:
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
edit.remove("yourKey");
edit.commit();
}
}
what you have to do is that whenever the item is checked you are simply clearing the shared pref value. Hope it helps
thanks to all, i got the solution in my code working fine.
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
restart:
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
//editor.remove("username").commit();
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
addmembers.remove(k);
edit.remove("yourKey");
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
break restart;
}
}
}
}
catch (Exception ex){
ex.toString();
}
the code is working fine to me.

How to get the index of the clicked ItemizedIconOverlay in OSM

How do i get the index position of the ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay when the user taps the icon? For example, when a user taps/clicks the first icon it should get the integer 0
List<GeoPoint> nodes = nodeCoordinates();
ArrayList<OverlayItem> anotherOverlayItemArray = new ArrayList<>();
Drawable newMarker = getResources().getDrawable(R.drawable.marker_node);
for(int i = 0; i < nodes.size(); i++) {
anotherOverlayItemArray.add(new OverlayItem("Road", "Nodes", nodes.get(i)));
anotherOverlayItemArray.get(i).setMarker(newMarker);
}
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<>(
this, anotherOverlayItemArray, null);
map.getOverlays().add(anotherItemizedIconOverlay);
There's an example here
https://github.com/osmdroid/osmdroid/blob/master/OpenStreetMapViewer/src/main/java/org/osmdroid/samplefragments/data/SampleMilitaryIconsItemizedIcons.java
ack, formatting issues....
`
itemOverlay = new ItemizedOverlayWithFocus<>(new ArrayList(),
new ItemizedIconOverlay.OnItemGestureListener() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
Toast.makeText(
context,
"Item '" + item.getTitle() + "' (index=" + index
+ ") got single tapped up", Toast.LENGTH_LONG).show();
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
Toast.makeText(
context,
"Item '" + item.getTitle() + "' (index=" + index
+ ") got long pressed", Toast.LENGTH_LONG).show();
return false;
}
}, context);
`

how to change the color of text partially in android

I have a sentence that contains message to be posted to the server like wow! superb pic #superb #pic #111 #222 enjoyed the pic
I want to extract the hastags and make them colored and leaving the rest of the text intact.
I tried the following code but not working.
private void spannableOperationOnHastag() {
mPostMessage = edPostMessage.getText().toString().trim();
String strPreHash = null;
String strHashText = "";
if (mPostMessage.contains("#")) {
try {
int index = mPostMessage.indexOf("#");
strPreHash = mPostMessage.substring(0, index);
SpannableString spannableString = new SpannableString(strPreHash);
String strHashDummy=mPostMessage.substring(index, mPostMessage.length());
int hashCount= StringUtils.countMatches(strHashDummy, "#"); // check for number of "#" occurrence and run forloop for getting the number of hastags in the string
int hasIndex=0;
for (int i = 0; i <hashCount ; i++) {
strHashText = strHashText+strHashDummy.substring(hasIndex, strHashDummy.indexOf(' '))+" ";
hasIndex =strHashText.indexOf(" "); // updating new space(" ") position in the index variable
}
SpannableString spannableStringBlue = new SpannableString(strHashText);
spannableStringBlue.setSpan(new ForegroundColorSpan(PublishPostActivity.this.getResources().getColor(R.color.blue)), 0, strHashText.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
} catch (Exception e) {
Log.d(TAG, "validatePostMessage() called with " + "e = [" + e + "]");
}
}
}
I solved the problem my self . I any one needs it can refer this code :)
private void spannableOperationOnHastag() throws Exception{
mPostMessage = edPostMessage.getText().toString()+" "; // extra space for spannable operations
List<Integer> listStartPos = new ArrayList<>();
List<Integer> listEndtPos = new ArrayList<>();
if (mPostMessage.contains("#")){
for (int i = 0; i < mPostMessage.length(); i++) {
if (mPostMessage.charAt(i) == '#') {
listStartPos.add(i);
Log.d(TAG, "startIndex of # = " + i);
}
}
for (int i = 0; i < listStartPos.size(); i++) {
int endIndex = mPostMessage.indexOf(' ', listStartPos.get(i));
listEndtPos.add(endIndex);
Log.d(TAG, "endIndex of # " + (endIndex));
}
SpannableString spanned = SpannableString.valueOf(mPostMessage);
for (int i = 0; i < listStartPos.size(); i++) {
spanned = new SpannableString(spanned);
spanned.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), listStartPos.get(i), listEndtPos.get(i), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.d(TAG, "substring " + mPostMessage.substring(listStartPos.get(i), listEndtPos.get(i) + 1));
}
mPostMessage.trim(); // removing extra space.
edPostMessage.setText(null);
edPostMessage.setText(spanned);
}
}
I see you've just posted your own answer, but as I'd nearly finished typing this up I thought I'd go ahead and post this anyway :). I typed it just now without an IDE so it may not be perfect.
private static SpannableString convertTextColorsAtChar(char trigger, String inputText) {
SpannableString spannedText = new SpannableString(inputText);
if (!inputText.contains(trigger)) {
return spannedText;
}
ArrayList<int[]> indexArr = getIndexes(trigger, inputText.toCharArray());
for (int[] indexes : indexArr) {
spannedText.setSpan(new ForegroundColorSpan(Color.RED), indexes[0], indexes[1], Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
returned spannedText;
}
private static ArrayList<int[]> getIndexes(char trigger, char[] inputText) {
ArrayList<int[]> values = new ArrayList<int[]>();
int firstIndex = -1;
int secondIndex; = -1
for (int i = 0; i < inputText.length; i++) {
if (firstIndex != -1 && inputText[i] == ' ') {
secondIndex = i;
values.add(new int[] { firstIndex, secondIndex });
firstIndex = secondIndex = -1;
}
if (trigger == inputText[i]) {
firstIndex = i;
}
}
return values;
}
You'd then call it with convertTextColorsAtChar('#', editText.getText().toString());
change your code as below
SpannableString spannableStringBlue = new SpannableString(strHashText);
spannableStringBlue.setSpan(new ForegroundColorSpan(new ForegroundColorSpan(Color.BLUE), 0, strHashText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
edPostMessage.setText(null); // clearing old string
edPostMessage.append(spannableString); // setting extracted coloured text
edPostMessage.append(spannableStringBlue);
SpannableStringBuilder builder = new SpannableStringBuilder();
String yourSentence = "Pic #superb #pic #111 #222 enjoyed the pic";
String [] newSent = yourSentence.split(" ");
for(int count = 0; count < newSent.length; count++){
if(newSent[count].contains("#")){
SpannableString redSpannable= new SpannableString(newSent[count]);
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, newSent[count].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Log.v("Test", "color_string" + newSent[count]);
builder.append(redSpannable+" ");
} else{
builder.append(newSent[count]+" ");
Log.v("Test", "normal_string" + newSent[count]);
}
}
holder.PhName.setText(builder, TextView.BufferType.SPANNABLE);

Compare String with Bubble Sort Algorithm

I have a program that will fetch several String from database (announcementId, and announcementTitle),
then for every string fetched from the database, I want to compare each of them (Compare all the fetched announcementId),
if the string (announcementId) has different value then it will create a new Button using the announcementTitle as it's(the button) value fetch from database.
I tried to learn how, and found out that bubble sort algorithm can be used in this case, but there is some error in the program.. Index out of bound exception..
Then I tried some code and tried to change the array, but it still didnt work.
Could you please take a look at my code and tell me where is the error and the best way to fix the error
This is my code :
myDb = new Database(ViewAllAnnouncement.this);
myDb.open();
totalAnnouncement = myDb.countHowManyAnnouncement(username);
String temp = Integer.toString(totalAnnouncement);
//Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
String[] announcementTitle = myDb.fetchMyAnnouncement(username);
String[] announcementId = myDb.fetchAnnouncementId(username);
for (int i = 0; i < totalAnnouncement; i++) {
for (int j = 0; j < totalAnnouncement - i; j++) {
if (j > 0 || j < totalAnnouncement-i) {
if (!announcementId[j].equals(announcementId[i])) {
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
}
}
}
}
myDb.close();
And this is my method to return the announcementId
public String[] fetchAnnouncementId(String Username) {
// TODO Auto-generated method stub
int i = 0;
String Query = "SELECT b." + ANNOUNCEMENT_ID + " FROM "
+ MS_GROUP_DETAIL + " a, " + MS_ANNOUNCEMENT_DETAIL + " b, "
+ MS_ANNOUNCEMENT + " c WHERE a." + GROUP_ID + " = b."
+ GROUP_ID + " AND b. " + ANNOUNCEMENT_ID + " = c."
+ ANNOUNCEMENT_ID + " AND a." + MEMBER_USERNAME + " =? ORDER BY b." +ANNOUNCEMENT_ID;
Cursor c = ourDatabase.rawQuery(Query, new String[] { Username });
String temp[] = new String[c.getCount()];
int iArray = c.getColumnIndex(ANNOUNCEMENT_ID);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
temp[i] = c.getString(iArray);
i++;
}
c.close();
return temp;
}
If bubble sort is the answer you must have misunderstood the question. I strongly recommend you just add
ORDER BY announcementId
to the end of your query. That way the database will sort by your column for you.
Edit
You could use
ORDER BY 1
to sort by the first column (and omit the name). And, then your code should look something like
for (int i = 0; i < totalAnnouncement - 1;) {
int j = i + 1;
for (; j < totalAnnouncement; j++) {
if (!announcementId[j].equals(announcementId[i])) {
break;
}
}
// j is the first value where the announcementId changes
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
i = j; // <-- assign j to i.
}

Categories