Compare String with Bubble Sort Algorithm - java

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.
}

Related

I want to merge the total price and quantity of the item in cart which is selected multiple times from movies list instead of same listings multiple

The problem lies in section where i am getting and sending results. some problem with the logic is there because the items of same kind are listed multiple times instead of updating existing row
when i add same item again it generates another row and post it there instead of updating existing same item row
public class MainActivity extends AppCompatActivity
{ ArrayList<cinema> cinemaArrayList=new ArrayList<cinema>();
ListView listView;
TextView total1;
int total12;
String quantity="";
int id;
ArrayList<String> cartItems = new ArrayList<String>();
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
if (result.getResultCode() == RESULT_OK && data != null) {
id = data.getIntExtra("id", 0);
total12 += data.getIntExtra("total", 0);
total1.setText("Total: " + total12 + "$");
String name = data.getStringExtra("name");
String price = data.getStringExtra("price");
quantity = data.getStringExtra("quantity");
int j=0;
if (cartItems.size() > 0) {
for (int i = 0; i<cartItems.size(); ) {
String[] info = cartItems.get(i).toString().split(",");
String name1 = info[0];
String quantity1 = info[1];
String price1 = info[2];
String id1 = info[3];
if (id == Integer.parseInt(id1)) {
j = Integer.parseInt(quantity1) + Integer.parseInt(quantity);
String item = name1 + "," + j + "," + price1 + "," + (Integer.parseInt(price) * j+","+id1 );
cartItems.set(i, item);
break;
} else {
i++;
}
}
}
if(j==0){
String item = name + "," + quantity + "," + price + "," + (Integer.parseInt(price) * Integer.parseInt(quantity)) + "," + id;
cartItems.add(item);
}}
if(result.getResultCode() == RESULT_OK && data == null){
total12=0;
total1.setText("Total: 0 $");
cartItems.clear();
}
}
});

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

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();
}
};
}

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 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);

This is making my program freeze

every time this starts my program freezes, and I can't figure out why.
It doesn't give any errors, it just freezes.
Is it possible I've created some kind of endless loop?
public static String[] DataVoorList(int coureur) throws SQLException{
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
int i=0;
while (rs.next()){
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
i++;
int codeInt = rs.getInt("rd_code");
String code = ""+codeInt;
datalijst.add(i, code);
i++;
}
return Race.StringDataVoorList(datalijst);
}
public static String[] StringDataVoorList(ArrayList invoer){
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
return uitvoer;
}
EDIT: I've solved the increment. However, it still freezes.
EDIT 2: I think I have located the problem (but I can be wrong)
public static String[] DataVoorList(int coureur) throws SQLException {
System.out.println("stap 1");
ArrayList datalijst = new ArrayList();
String query = ""
+ "SELECT rd_datum, rd_locatie, rd_code "
+ "FROM racedag WHERE rd_code in( "
+ "SELECT i_rd_code "
+ "FROM Inschrijvingen "
+ "WHERE i_c_nummer = " + coureur + ");";
ResultSet rs = Database.executeSelectQuery(query);
System.out.println("stap 2");
int i = 0;
while (rs.next()) {
String datum = rs.getString("rd_datum");
String locatie = rs.getString("rd_locatie");
String totaal = "" + datum + " - " + locatie;
datalijst.add(i, totaal);
System.out.println("stap 3");
i++;
int codeInt = rs.getInt("rd_code");
String code = "" + codeInt;
datalijst.add(i, code);
i++;
System.out.println("stap 4");
}
return Race.StringDataVoorList(datalijst);
(I've changed the while loop to a for loop)
public static String[] StringDataVoorList(ArrayList invoer) {
int lengte = invoer.size();
String[] uitvoer = new String[lengte];
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = "" + invoer.get(i);
}
return uitvoer;
}
}
this is being called from here:
public MijnRacedagenScherm() throws SQLException{
initComponents();
int gebruiker = Inloggen.getNummer();
String[] DataVoorList = Race.DataVoorList(2);
int lengte = DataVoorList.length;
System.out.println("resultaat is " + DataVoorList[0]);
int i = 0;
while (i < lengte) {
ListRacedagenCoureur.setListData(DataVoorList);
i = i + 2;
}
System.out.println("lengte is " + lengte);
}
This is a new screen, but in the previous screen I get a unreported SQL exception over this:
private void ButtonZienRacedagActionPerformed(java.awt.event.ActionEvent evt) {
new MijnRacedagenScherm().setVisible(true);
}
Well, um... In this section:
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
Where is i incremented?
Indeed it is, this
int i =0;
while (i < uitvoer.length){
uitvoer[i] = ""+invoer.get(i);
}
You never increment i.
As stated problem is in your while loop.
for loop is more suitable for iterating over indexed data type
for (int i = 0; i < uitvoer.length; i++) {
uitvoer[i] = ""+invoer.get(i);
}
How many rows are you processing? The way you append strings is quite slow, maybe it's not freezing anymore but just taking a long time to complete.

Categories