I'm trying to do something reallllly simple that apparently is extremely difficult in android.
I just want to compare two strings to see if they are equal.
I have a temp variable with the value "Location"
I have debugged this and it does indeed contain Location...
So I tried this at first
if(temp == "Location") { //do something }
But I already know that doesn't work. I then tried all the possible functions for a string such as:
.equals
.contains
.ignoreCaseEquals
etc...
If anyone has any idea what to do please help. This is really getting annoying.
EDIT:
Here is the function where I'm comparing the strings for those of you who want to see.
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equals("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
equals does work. If temp.equals("Location") returns false, then your temp variable does not refer to a string with the value "Location".
There may be unprintable characters or other oddities about the string - I suggest you look at the length of the string to check. Alternatively, there can be other characters which look like the ASCII characters, but aren't. In the debugger, try examining the array and get at the underlying char array - check the Unicode value of each character.
if(temp.equals("Location"))
{
//your code here
}
does not work
try this
if(temp.contains("Location"))
{
//your code here
}
try like
if(temp.equals("Location")) { //do something }
and
while (!temp.equals("")){
if your variable temp is a String, you can also used the method compareTo(String).
if (temp.compareTo("Location") == 0)
{
//do something
}
I am doing same scenario , its working fine.
String result = responsePrimitiveData.toString();
if(!result.equals("0")){
}
Try doing this:
if (temp.toLowerCase().compareTo("location") == 0)
public String[] getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
// check to see if readline equals Location
Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.toString().equalsIgnoreCase("Location")
{
groups[tempGroupCount] = temp;
tempGroupCount++;
}
Log.w("HERasdfsafdsafdsafE", temp);
//start for-loop to test to get child info
//for(temp = my_buffer.readLine(); temp != "Location" && temp != null; groupCount++, childrenCount++){
//children[groupCount][childrenCount] = temp;
//}
temp = my_buffer.readLine();
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
return groups;
}
first try to convert "temp" into string then compare it, apply this may helps you
you may try the following to find out where your problem is.
final String LOCATION = "Location"; // just to make sure we use the very same character sequence
if (temp.equals(LOCATION)
{
/* your code here */
}
else
{
System.out.println("Location : " + Arrays.toString(LOCATION.getBytes(Charset.forName("UTF-8"))));
System.out.println("temp : " + Arrays.toString(temp.getBytes(Charset.forName("UTF-8"))));
}
This should print the byte representation of both Strings to standard out. If equals() returns false, the strings differ. Because of unprintable characters or similar looking characters it's sometimes difficult to find the difference. But the byte representation should show you.
(I'm not an android programmer, so I hope the functions exist on android JVM. And sorry for any typos and missing brackets - if any ;-)
Related
This seemed like a really trivial issue, but I'm trying to write an array of booleans to a file and then read them back into the array. I can verify that the file is being created properly:
true
false
true
false
false
false
But when I try to read it back, I end up with an array completely full of false. Here's my reading code:
bools = new boolean[bools.length];
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String temp;
int i = 0;
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
reader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
}
// now output the resulting array
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
And here's the output I get:
true!
false!
true!
false!
false!
false!
false!
false!
false!
false!
false!
false!
The part that drives me bonkers is the array is set properly when I check it as I read (in the while loop), but it's wrong when I check the array at the end (in the for loop).
It may also be helpful to know that bools is a property of the class
Please excuse my noobishness.
Thanks!
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
You are putting everything at the same location. Increment your iterator variable and it will work.
Your not updating i value. First time your getting properly because your printing values directly from file.
It gives a message saying: "Null pointer access: The variable CharacterList can only be null at this location", when I think it should be filled from the FileReader.Read() method:
public String[] ReadPeopleFile(String[] PeopleList, FileReader PeopleReader){
char CharacterList[];///Soon parsed into a string list, by delimiting and separating into two string arrays,
CharacterList = null;
String ParseString = null;
try {
PeopleReader.read(CharacterList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseString = CharacterList.toString();
PeopleList = ParseString.split(";");
return PeopleList;
}
CharacterList is not going to be assigned unless you assign it. You need something more like this:
char characterList[] = new char[1000]; // I'm assuming that 1000 is enough here
int numChars = peopleReader.read(characterList); // I've changed PeopleReader to proper camel-case
String parseString = new String(characterList, 0, numChars);
I'm actually skipping some details here. You should really look at the API documentation for FileReader and maybe find some file reading examples.
Here are faced with the problem of sorting files. Choose the files from the folder Asset. How to sort files in ascending?
Here is my code:
//fillGrid
private void fillGridAdapter(int cat) {
ASSETS_IMAGE_DIR = imagePath[cat];
addImages(getImages(imagePath[cat]));
}
//Adds the files
private void addImages(String[] temp){
imBitmap = new Bitmap[temp.length];
if(temp != null) {
for(int i = 0; i < temp.length; i++){
try {
imBitmap[i] = getBitmapFromAsset(imagePath[g.getImageCat()]+"/"+temp[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private String[] getImages(String f){
try {
AssetManager assetManager = getResources().getAssets();
String[] temp = assetManager.list(f);
Arrays.sort(temp);
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
After assetManager.list(f) String[] temp - (1.jpg, 10.jpg, 12.jpg ... 9.jpg). After Arrays.sort(temp) - (1.jpg, 10.jpg, 12.jpg ... 9.jpg). And I need to - 1.jpg, 2.jpg, 3.jpg... n.jpg.
Use Arrays.sort(T[] a, Comparator c)
Here's an example http://www.coderanch.com/t/378718/java/java/sort-array-files-directories
It sounds like you want to sort the files into numeric order ... not lexical order.
To achieve this, you will need to split the pathnames into a numeric and non-numeric segments. For the numeric segment(s) you need to parse the segment as an integer and sort based on the integer values.
It looks like your files are of the form <number>.<suffix>, so the splitting should be simple.
This logic needs to be implemented in the compare method of a Comparator which you provides a parameter to sort.
I'm trying to contain all matches found into a text document, I have been banging my head on my desk for the past 3 hours and figured it would be time I asked for help.
My current issue is with the List<String> and I'm not sure if it because the information entered is wrong or if it's my file print methods. It does not print to file and with other means of printing such as writer.println(returnvalue) and even then, it still only displays one of the matches and not all, I do have the matches appearing in console just to make sure they are showing and they are.
Edit2: Sorry this would be my first question on stackoverflow, I guess my question is How would you print all the data from a list array to a text file?
Edit3: My newest problem is printing out all matches i am currently stuck printing out the last match, any advice?
public static void RegexChecker(String TheRegex, String line){
String Result= "";
List<String> returnvalue = new ArrayList<String>();
Pattern checkRegex = Pattern.compile(TheRegex);
Matcher regexMatcher = checkRegex.matcher(line);
int count = 0 ;
FileWriter writer = null;
try {
writer = new FileWriter("output.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
while ( regexMatcher.find() ){
if (regexMatcher.group().length() != 0){
returnvalue.add(regexMatcher.group());
System.out.println( regexMatcher.group().trim() );
}
for(String str: returnvalue) {
try {
out.write(String.valueOf(returnvalue.get(i)));
writer.write(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Get the for out of while. You want to write to the file only after all matches have been added to the list. The for-each block needs some modifications as well.
The for-each construct gives you values from iteration over the collection. You need not obtain the values again using an index.
Try this:
while (regexMatcher.find()) {
if (regexMatcher.group().length() != 0) {
returnvalue.add(regexMatcher.group());
System.out.println(regexMatcher.group().trim());
}
}
try {
for (String str : returnvalue) {
writer.write(str + "\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Let's say I can a set of statements:
try {
String a = getProperty("a");
String b = getProperty("b");
String c = getProperty("c");
} catch(Exception e) {
}
Now, lets say property b was not found and the function throws an exception. In this case, how would I just continue or perhaps set b to null without having to write a try-catch block for each property? I mean, a,b,c exist but sometime they might not be found at all during which an exception is thrown.
Assuming you can't change the function so that it returns null when the property isn't found, you are kind of stuck wrapping everything in its own try catch block -- especially if you want for every value that can be retrieved to be retrieved (as opposed to letting the first value that fails cancel the whole operation.)
If you have a lot of these properties to retrieve, perhaps it would be cleaner to write a helper method to use:
String getPropertySafely(String key) {
try {
return getProperty(key);
} catch (Exception e) {
return null;
}
}
You have to put a try-catch around each statement. There is no continue (like there is in ON ERROR ... RESUME blocks in VB). Instead of:
String a = null;
try {
a = getProperty("a");
} catch(Exception e) {
...
}
String b = null;
try {
b = getProperty("b");
} catch(Exception e) {
...
}
String c = null;
try {
c = getProperty("c");
} catch(Exception e) {
...
}
you could write:
public String getPropertyNoException(String name) {
try {
return getProperty(name);
} catch (Exception e) {
return null;
}
}
Personally I think a getProperty() is a poor candidate for throwing exceptions just for all this extra boilerplate required
Since you are using the same function each time you might be able to put this in a loop:
String[] abc = new String[3];
String[] param = {"a", "b", "c"};
for (int i = 0; i < 3; i++) {
try {
abc[i] = getProperty(param[i]);
} catch(Exception e) {
}
}
but this is rather contrived and would only be useful for a large number of properties. I suspect you will have to simple write 3 try-catch.
You should reconsider how getProperty is handled if you plan to use many of them because there isn't a plain way to do it.
You can exploit finally statement but you still need a try-catch for every call.