cannot read string result from MYSQL - if-statement

I want to have an if else statement inside a loop when getting the results of
data from mysql .. However the if statement cannot read the result.. but the codes are perfectly I see the problem in my if else condition.
here is my Code from my asynctask
for (int i = 0; i < markers.length(); i++) {
JSONObject c = markers.getJSONObject(i);
// Storing each json item in variable
Double LAT = c.getDouble(TAG_LAT);
Double LNG = c.getDouble(TAG_LNG);
String color = c.getString(TAG_STATUS);
String red = "ongoing";
String green = "firedout";
if (color == red){
LatLng position = new LatLng(LAT, LNG);
status.add(new MarkerOptions()
.title(color)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
.position(position));
// adding HashList to ArrayList
}
if (color == green){
LatLng position = new LatLng(LAT, LNG);
status.add(new MarkerOptions()
.title(color)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(position));
// adding HashList to ArrayList
}
}

Equivalent String values are not guaranteed to be unique in Java. In other words, there can be two String objects with exactly the same value.
String s1 = "ongoing";
String s2 = new String(s1);
System.out.println(s1 == s2); // false!
System.out.println(s1.equals(s2)); // true :)
Therefore, you must say:
if (red.equals(color)) {
// do something
}

Related

If else not working in android inside for and while loop

public void LoadRoutine() {
TableRow tbrow0 = new TableRow(getActivity());
//String[] mStrings = new String[9];
tbrow0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow0.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String c : TimeSlotSummer) {
TextView tv0 = new TextView(getActivity());
tv0.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv0.setGravity(Gravity.CENTER);
tv0.setTextSize(12);
tv0.setHeight(40);
tv0.setWidth(76);
tv0.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv0.setTextColor(Color.parseColor("#000000"));
tv0.setPadding(1, 1, 1, 1);
tv0.setText(c);
tv0.setBackgroundColor(R.id.tableRowid);
tbrow0.addView(tv0);
}
tableLayout.addView(tbrow0);
String dept = GlobalClass.userDepartment;
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(getActivity());
databaseAccess.Open();
String faccode = GlobalClass.faculty_code;
Cursor cRoutine = databaseAccess.getRoutine("Sunday",dept);
if (cRoutine.getCount() == 0) {
Toast.makeText(getActivity(),"No Data in Table",Toast.LENGTH_LONG).show();
}
else{
while (cRoutine.moveToNext())
{
String[] mStrings = new String[10];
mStrings[0] = cRoutine.getString(2);
mStrings[1] = cRoutine.getString(4);
mStrings[2] = cRoutine.getString(5);
mStrings[3] = cRoutine.getString(6);
mStrings[4] = cRoutine.getString(7);
mStrings[5] = cRoutine.getString(8);
mStrings[6] = cRoutine.getString(9);
mStrings[7] = cRoutine.getString(10);
mStrings[8] = cRoutine.getString(11);
TableRow tbrow1 = new TableRow(getActivity());
tbrow1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tbrow1.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
for (String cls:mStrings) {
TextView tv1 = new TextView(getActivity());
tv1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv1.setGravity(Gravity.CENTER);
tv1.setTextSize(12);
tv1.setWidth(75);
tv1.setHeight(37);
tv1.setBackgroundColor(Color.parseColor("#FFFFFF"));
tv1.setPadding(1, 1, 1, 1);
tv1.setBackgroundColor(R.id.tableRowid);
tv1.setText(cls);
tv1.setTextColor(Color.parseColor("#FF0000"));
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
tbrow1.addView(tv1);
}
tableLayout.addView(tbrow1);
}
}
}
Inside the last for loop, without if-else, it works properly, but with if-else it is not working, that is apps shut down and mobile restart again.
Any one help me, I want to check some substring, then text color will change, otherwise color normal.
It would help if you posted a stack trace but if the crash occurs here:
if(cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));
The only explanation is that you get a NullPointerException on cls because tv1 is obviously not null if it did not crash before.
Use this code instead:
if(cls != null && cls.contains(faccode))
tv1.setTextColor(Color.parseColor("#000000"));
else
tv1.setTextColor(Color.parseColor("#FF0000"));

How to sort a string without sorting commands

I have an assignment for one of my classes where I need to sort a string alphabetically without using any commands besides the simple ones that are already in here. Whenever I use it, it works for the most part except it will leave words like Fred & Eric, or Hazel & Ian (first letter's are next to each other in the alphabet). The string that is being compared to the others is set as "two" then all others are compared against it. The B string is just one that is being changed with the A string. If anyone knows why this is, that would be greatly appreciated!
for (int ct = 0; ct < kh; ct++){
hold = A[ct];
bool pass = false;
for (int ct2 = ct+1; ct2 < kh; ct2++){
two = A[ct2];
if (two[0] < hold[0]){
save = A[ct2];
A[ct2] = A[ct];
A[ct] = save;
hold = two;
save = B[ct2];
B[ct2] = B[ct];
B[ct] = save;
}
else if (two[0] == hold[0]){
if (two[1] < hold [1]){
save = A[ct2];
A[ct2] = A[ct];
A[ct] = save;
hold = two;
save = B[ct2];
B[ct2] = B[ct];
B[ct] = save;
}
}
else if (two[1] == hold[1]){
if (two[2] < hold [2]){
save = A[ct2];
A[ct2] = A[ct];
A[ct] = save;
hold = two;
save = B[ct2];
B[ct2] = B[ct];
B[ct] = save;
}
}
}
}

Replacing dynamic variable in string UNITY

I am making a simple dialogue system, and would like to "dynamise" some of the sentences.
For exemple, I have a Sentence
Hey Adventurer {{PlayerName}} !
Welcome in the world !
Now In code I am trying to replace that by the real value of the string in my game. I am doing something like this. But it doesn't work. I do have a string PlayerName in my component where the function is situated
Regex regex = new Regex("(?<={{)(.*?)(?=}})");
MatchCollection matches = regex.Matches(sentence);
for(int i = 0; i < matches.Count; i++)
{
Debug.Log(matches[i]);
sentence.Replace("{{"+matches[i]+"}}", this.GetType().GetField(matches[i].ToString()).GetValue(this) as string);
}
return sentence;
But this return me an error, even tho the match is correct.
Any idea of a way to do fix, or do it better?
Here's how I would solve this.
Create a dictionary with keys as the values you wish to replace and values as what you will be replacing them to.
Dictionary<string, string> valuesToReplace;
valuesToReplace = new Dictionary<string, string>();
valuesToReplace.Add("[playerName]", "Max");
valuesToReplace.Add("[day]", "Thursday");
Then check the text for the values in your dictionary.
If you make sure all of your keys start with "[" and end with "]" this will be quick and easy.
List<string> replacements = new List<string>();
//We will save all of the replacements we are about to perform here.
//This is done so we won't be modifying the original string while working on it, which will create problems.
//We will save them in the following format: originalText}newText
for(int i = 0; i < text.Length; i++) //Let's loop through the entire text
{
int startOfVar = 9999;
if(text[i] == '[') //We have found the beginning of a variable
{
startOfVar = i;
}
if(text[i] == ']') //We have found the ending of a variable
{
string replacement = text.Substring(startOfVar, i - startOfVar); //We have found the section we wish to replace
if (valuesToReplace.ContainsKey(replacement))
replacements.Add(replacement + "}" + valuesToReplace[replacement]); //Add the replacement we are about to perform to our dictionary
}
}
//Now let's perform the replacements:
foreach(string replacement in replacements)
{
text = text.Replace(replacement.Split('}')[0], replacement.Split('}')[1]); //We split our line. Remember the old value was on the left of the } and the new value was on the right
}
This will also work much faster, since it allows you to add as many variables as you wish without making the code slower.
Using Regex.Replace method, and a MatchEvaluator delegate (untested):
Dictionary<string, string> Replacements = new Dictionary<string, string>();
Regex DialogVariableRegex = new Regex("(?<={{)(.*?)(?=}})");
string Replace(string sentence) {
DialogVariableRegex.Replace(sentence, EvaluateMatch);
return sentence;
}
string EvaluateMatch(Match match) {
var matchedKey = match.Value;
if (Replacements.ContainsKey(matchedKey))
return Replacements[matchedKey];
else
return ">>MISSING KEY<<";
}
This is kind of old now, but I figured I'd update the accepted code above. It won't work since the start index is reset every time the loop iterates, so setting startOfVar = i gets completely reset by the time it hits the closing character. Plus there are problems if there's an open bracket '[' and no closing one. You can also no longer use those brackets in your text.
There's also setting the splitter to a single character. It tests fine, but if I set my player name to "Rob}ert", that will cause problems when it performs the replacements.
Here is my updated take on the code which I've tested works in Unity:
public string EvaluateVariables(string str)
{
Dictionary<string, string> varDict = GetVariableDictionary();
List<string> varReplacements = new List<string>();
string matchGuid = Guid.NewGuid().ToString();
bool matched = false;
int start = int.MaxValue;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '{')
{
if (str[i + 1] == '$')
{
start = i;
matched = true;
}
}
else if (str[i] == '}' && matched)
{
string replacement = str.Substring(start, (i - start) + 1);
if (varDict.ContainsKey(replacement))
{
varReplacements.Add(replacement + matchGuid + varDict[replacement]);
}
start = int.MaxValue;
matched = false;
}
}
foreach (string replacement in varReplacements)
{
str = str.Replace(replacement.Split(new string[] { matchGuid }, StringSplitOptions.None)[0], replacement.Split(new string[] { matchGuid }, StringSplitOptions.None)[1]);
}
return str;
}
private Dictionary<string, string> GetVariableDictionary()
{
Dictionary<string, string> varDict = new Dictionary<string, string>();
varDict.Add("{$playerName}", playerName);
varDict.Add("{$npcName}", npcName);
return varDict;
}

Can't get the proper Index to return

Alright, so firstly I want to thank everyone for helping me so much in the last couple weeks, here's another one!!!
I have a file and I'm using Regex to find how many times the term "TamedName" comes up. That's the easy part :)
Originally, I was setting it up like this
StreamReader ff = new StreamReader(fileName);
String D = ff.ReadToEnd();
Regex rx = new Regex("TamedName");
foreach (Match Dino in rx.Matches(D))
{
if (richTextBox2.Text == "")
richTextBox2.Text += string.Format("{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
else
richTextBox2.Text += string.Format("\n{0} - {1:X} - {2}", Dino.Value, Dino.Index, ReadString(fileName, (uint)Dino.Index));
}
and it was returning completely incorrect index points, as pictured here
I'm fairly confident I know why it's doing this, probably because converting everything from a binary file to string, obviously not all the characters are going to translate, so that throws off the actual index count, so trying to relate that back doesn't work at all... The problem, I have NO clue how to use Regex with a binary file and have it translate properly :(
I'm using Regex vs a simple search function because the difference between each occurrence of "TamedName" is WAY too vast to code into a function.
Really hope you guys can help me with this one :( I'm running out of ideas!!
The problem is that you are reading in a binary file and the streamreader does some interpretation when it reads it into a Unicode string. It needed to be dealt with as bytes.
My code is below.(Just as an FYI, you will need to enable unsafe compilation to compile the code - this was to allow a fast search of the binary array)
Just for proper attribution, I borrowed the byte version of IndexOf from this SO answer by Dylan Nicholson
namespace ArkIndex
{
class Program
{
static void Main(string[] args)
{
string fileName = "TheIsland.ark";
string searchString = "TamedName";
byte[] bytes = LoadBytesFromFile(fileName);
byte[] searchBytes = System.Text.ASCIIEncoding.Default.GetBytes(searchString);
List<long> allNeedles = FindAllBytes(bytes, searchBytes);
}
static byte[] LoadBytesFromFile(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
//BinaryReader br = new BinaryReader(fs);
//StreamReader ff = new StreamReader(fileName);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
fs.Close();
return ms.ToArray();
}
public static List<long> FindAllBytes(byte[] haystack, byte[] needle)
{
long currentOffset = 0;
long offsetStep = needle.Length;
long index = 0;
List<long> allNeedleOffsets = new List<long>();
while((index = IndexOf(haystack,needle,currentOffset)) != -1L)
{
allNeedleOffsets.Add(index);
currentOffset = index + offsetStep;
}
return allNeedleOffsets;
}
public static unsafe long IndexOf(byte[] haystack, byte[] needle, long startOffset = 0)
{
fixed (byte* h = haystack) fixed (byte* n = needle)
{
for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext < hEnd; hNext++)
for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)
if (++nInc == nEnd)
return hNext - h;
return -1;
}
}
}
}

Output formatted text to Screen

I have a vector that stores pairs. Each pair contains a CString and a bool.
If the CString is meant to be underlined then bool is true, else it is false.
I want to output the text in the vector to the screen making sure that text is underlined in the correct places.
So far I have the following code:
void CEmergenceView::AppendText( CString msg ) {
int nBegin;
CRichEditCtrl &rec = GetRichEditCtrl();
nBegin = rec.GetTextLength();
rec.SetSel(nBegin, nBegin); // Select last character
rec.ReplaceSel(msg); // Append, move cursor to end of text
rec.SetSel(-1,0); // Remove Black selection bars
nBegin = rec.GetTextLength(); // Get New Length
rec.SetSel(nBegin,nBegin); // Cursor to End of new text
// Fix annoying "do you want to save your changes?" when program exits
GetDocument()->SetModifiedFlag(FALSE); // -Optional- (sometimes you want this)
}
int nEnd = 0;
// loop through start of text to end of text
for(int k = 0; k < groups.size(); k++) {
rEditCtrl.SetSel(nEnd, nEnd);
rEditCtrl.GetSelectionCharFormat(cf);
if(groups.at(k).second) {
if(!cf.dwEffects & !CFE_UNDERLINE) {
CRichEditView::OnCharUnderline();
}
}
else if(!groups.at(k).second) {
if(cf.dwEffects & CFE_UNDERLINE) {
CRichEditView::OnCharUnderline();
}
}
AppendText(groups.at(k).first);
nEnd = nEnd + (groups.at(k).first.GetLength());
}
However, this is not underlining at all....Can anyone tell me what I'm doing wrong?? Thanks!
I think you should implement the OnCharUnderline
Try to call yours own function instead of the default one:
You can get it from here:
void CMyRichEditView::OnCharUnderline ()
{
CHARFORMAT2 cf;
cf = GetCharFormatSelection();
if (!(cf.dwMask & CFM_UNDERLINE) || !(cf.dwEffects & CFE_UNDERLINE))
cf.dwEffects = CFE_UNDERLINE;
else
cf.dwEffects = 0;
cf.dwMask = CFM_UNDERLINE;
SetCharFormat(cf);
}