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);
`
Related
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();
}
};
}
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.
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.
I made an app to read values from the database and send messages through the smsManager and it was perfectly fine but all of a sudden it stopped working, Anybody have any idea what could be the cause? It returns sent status but the messages are not being sent in reality. Here is the code:
package com.brs;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.telephony.SmsManager;
import android.widget.Toast;
/**
* Created by Sahil on 17-06-2015.
*/
public class Sending extends IntentService {
public static int cursor_count=0;
public Sending()
{
super("Sending");
}
SQLiteDatabase sqliteDatabase;
DatabaseHandler databasehandler;
Cursor cursor, cursor2;
protected void onHandleIntent(Intent workIntent) {
databasehandler = new DatabaseHandler(getApplicationContext());
sqliteDatabase = databasehandler.getReadableDatabase();
cursor = databasehandler.read_queue(sqliteDatabase);
cursor.moveToFirst();
System.out.println("The Vlaues for cursor : " + cursor.getCount());
//cursor_count = cursor.getCount();
cursor2 = databasehandler.read_polls(sqliteDatabase);
System.out.println("The Vlaues for cursor2 : " + cursor2.getCount());
int t = 0;
//To reach the first pending statement.
do {
String stats;
stats = cursor.getString(2);
System.out.println("The status is " + stats);
if (stats.matches("PENDING")) {
System.out.println("THE DEBUG CHECKER");
t = 1;
break;
}
} while (cursor.moveToNext());
if (t == 1)
{
do
{
String ques = "", opt1 = "", opt2 = "", opt3 = "", opt4 = "", opt5 = "", keyword = "", start_date = "", end_date = "", message = "";
int k = cursor.getInt(0);
System.out.println("The cursor index:" + k);
if (cursor2.moveToFirst())
{
do
{
int pol_id;
pol_id = cursor2.getInt(0);
if (pol_id == k)
{
ques = cursor2.getString(1);
opt1 = cursor2.getString(2);
opt2 = cursor2.getString(3);
opt3 = cursor2.getString(4);
opt4 = cursor2.getString(5);
opt5 = cursor2.getString(6);
keyword = cursor2.getString(7);
start_date = cursor2.getString(8);
end_date = cursor2.getString(9);
message = cursor2.getString(10);
break;
}
} while (cursor2.moveToNext());
}
for (int i = 0; i < 20; i++) {
int id;
String number;
String status;
id = cursor.getInt(0);
number = cursor.getString(1);
status = cursor.getString(2);
System.out.println("The id :" + id);
System.out.println("The number:" + number);
System.out.println("The status :" + status);
if (id == k) {
String sms;
if (message.matches("")) {
sms = ques + "\nA." + opt1 + "\nB." + opt2 + "\nC." + opt3 + "\nD." + opt4 + "\nE." + opt5 + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)";
} else {
sms = message + "\nSTART DATE:" + start_date + "\nEND DATE:" + end_date + "\nReply in the below given format:\n" + id + " " + keyword + " (A|B|C|D|E)\nResponses in Invalid format would not be processed.\nSent from GOLL_POLL";
}
try {
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentPI;
String SENT = "SMS_SENT";
sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
smsManager.sendTextMessage(number, null, sms, sentPI, null);
databasehandler.update_queue(id, number, "SENT");
} catch (Exception e) {
databasehandler.update_queue(id, number, "FAIL");
System.out.println("Message sending failed");
e.printStackTrace();
}
System.out.println("The status:" + cursor.getString(2));
if (cursor.moveToNext()) {
} else {
break;
}
}
else {
break;
}
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 40000);
cursor.moveToPrevious();
} while (cursor.moveToNext());
System.out.println("The end has been reached:");
}
}
}
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.
}