I am currently working on my own version of a glossary written in Java. Truthfully, this is of academic nature and I was hoping someone could point me in the first direction. Anyway, I am reading in text from a text file and putting the words and their corresponding definitions into a Map (Tree Map to be more specific). Everything works good from there. Everything is in the map as it should be.
Now I start to get to the part where I want to go into HTML and output the contents of the map. I know how to do that with iterators and that wasn't much of a problem. However, when I try to display the content mixed in with HTML I don't get all that I want. The page is ultimately supposed to look like this: http://cse.osu.edu/~weide/rsrg/sce/now/321/421/labs/lab10/glossary.html#book
And there is this particularly tricky part where if there's a term contained within a definition it should be clickable. Here is what I have so far. Again, if anyone could help me figure out why the main guts of the HTML aren't displaying I would appreciate it very much! By the way, the text file I'm getting things from is called: terms.txt, and the html file writing to is called glossary.html.
This is what I have so far:
public class Glossary {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Map<String, String> dictionary = new TreeMap<String, String>();
File htmlFile = new File(
"/Users/myname/Documents/workspace/Lab10/src/glossary.html");
File file = new File(
"/Users/myname/Documents/workspace/Lab10/src/terms.txt");
Writer out = new OutputStreamWriter(new FileOutputStream(htmlFile));
String term = null;
String def = null;
String key = null, value = null;
String lead = null;
String multiFinalDef = null;
Set<String> checkValues = new HashSet<String>();
String leftOver = null;
boolean check = false;
Scanner input = null;
try {
input = new Scanner(file);
while (input.hasNext()) {
String keepTrack;
boolean multi = false;
String line = input.nextLine();
term = line;
def = input.nextLine();
keepTrack = def;
while (def.length() > 0 && input.hasNext()) {
def = input.nextLine();
if (def.length() > 0) {
multiFinalDef = " " + keepTrack + def;
multi = true;
}
}
if (multi) {
dictionary.put(term, multiFinalDef);
} else {
dictionary.put(term, keepTrack);
}
checkValues.add(term);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.write("<HTML>\n");
out.write("<HEAD>\n");
out.write("</HEAD>\n");
out.write("<BODY>\n");
out.write("<H1>Glossary</H1>\n");
out.write("<HR /\n");
out.write("<H2>Index</H2>\n");
out.write("<UL>\n");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Set s = dictionary.entrySet();
Iterator iterator = s.iterator();
while (iterator.hasNext()) {
Map.Entry m = (Map.Entry) iterator.next();
// getKey is used to get key of map.
key = (String) m.getKey();
// getValue is used to get the value of the key in map.
value = (String) m.getValue();
// this is just so I know the output from the map is actually correct. And indeed it is.
System.out.println("Key:\t\t\tValue\n " + key + "\t\t\t " + value
+ "\n");
try {
out.write("<LI>" + key + "</LI>\n");
out.write("</UL>\n");
out.write("<HR />\n");
} catch (IOException e) {
e.printStackTrace();
}
}
out.write("<H2>Terms and Definitions</H2>\n");
out.write("<UL>\n" + "<P>\n");
iterator = s.iterator();
while (iterator.hasNext()) {
Map.Entry temp = (Map.Entry) iterator.next();
// getKey is used to get key of map.
String keyTwo = (String) temp.getKey();
// getValue is used to get the value of the key in map.
String valueTwo = (String) temp.getValue();
out.write("<H3><A NAME=\" " + keyTwo + "/><B><I><FONT COLOR=\"red\">"
+ keyTwo + "</FONT></I></B></LI></H3>\n");
for(String getTerm : checkValues){
if (valueTwo.contains(getTerm)) {
check = true;
int foundTermPosition = valueTwo.indexOf(getTerm);
lead = valueTwo.substring(0, foundTermPosition - 1);
//fix left over..
leftOver = valueTwo.substring(foundTermPosition, valueTwo.length());
out.write(lead);
out.write("" + keyTwo + "");
out.write(leftOver + "\n");
//out.write("</blockquote>\n");
}
}
if( check == false)
{
out.write(lead + " " + valueTwo);
}
}
//System.out.println(valueTwo + leftOver);
// used to put words defined in file mentioned in definition
// with hyperlinks to their associated locations, and output the
// definition.
out.write("</P>\n" + "</UL>\n");
out.write("</BODY>\n");
out.write("</HTML>");
out.close();
}
}
By the time your program reaches
out.write("<H2>Terms and Definitions</H2>\n");
out.write("<UL>\n" + "<P>\n");
while (iterator.hasNext()) {
...
the iterator doesn't have any more items left, as it gets exhausted on the first while loop a few lines before, while you're printing the index. To iterate through the map again, you'll need to call the iterator method again. So the block above would become:
out.write("<H2>Terms and Definitions</H2>\n");
out.write("<UL>\n" + "<P>\n");
iterator = s.iterator();
while (iterator.hasNext()) {
...
As I understand, you want to generate html documents. In my humble opinion, the best and generic approach in your case - use any of template engines. For example - Apache Velocity.
It takes a few minutes to look through this tutorial
Related
Hello fellow soldiers.
Obviously keys in hashmaps are unique. However, I've been trying to write a code that reads a csv file and then puts the key and value in the map. However, there are keys the same (every key is like 15 times in the csv file). In that case, it should make a sum of the values, and just return the key once.
How to do that? My code right now is as follows.
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(filepath));
} catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + "Bestand niet gevonden!");
System.exit(0);
}
//this is where we read lines
try {
while((line = br.readLine()) != null) {
String[] splitter = line.split(cvsSplitBy);
if(splitter[0] != "Voertuig") {
alldataMap.put(splitter[0], splitter[8]);
}
//MIGHT BE JUNK, DONT KNOW YET
/*if((splitter[0].toLowerCase()).contains("1")){
double valuekm = Double.parseDouble(splitter[8]);
license1 += valuekm;
System.out.println(license1);
}
else {
System.out.println("not found");
}*/
}
System.out.println(alldataMap);
TextOutput();
} catch (IOException ioex) {
System.out.println(ioex.getMessage() + " Error 1");
} finally {
System.exit(0);
}
So if I have the following info (in this case its the 0th and 8th word read every line in the csv file)
Apples; 299,9
Bananas; 300,23
Apples; 3912,1
Bananas;342
Bananas;343
It should return
Apples;Total
Bananas;Total
Try the following:
if( alldataMap.containsKey(splitter[0]) ) {
Double sum = alldataMap.remove(splitter[0]) + Double.parseDouble(splitter[8]);
allDataMap.put(splitter[0], sum );
} else {
alldataMap.put(splitter[0], Double.valueOf(splitter[8]) );
}
You can use putIfAbsent and compute since Java 8:
Map<String, Integer> myMap = new HashMap<>();
//...
String fruitName = /*whatever*/;
int qty = /*whatever*/;
myMap.putIfAbsent(fruitName, 0);
myMap.compute(fruitName, (k, oldQty) -> oldQty + qty);
You can use Map#containsKey() to check for an existing mapping, then if there is one use Map#get() to retrieve the value and add the new one, and finally Map#put() to store the sum:
if(map.containsKey(key))
map.put(key, map.get(key)+value);
else
map.put(key, value);
See here for the documentation of those methods.
i would use the merge for a map :
alldataMap.merge(splitter[0], Double.valueOf(splitter[8]), (oldVal, newVal) -> oldVal + newVal);
From doc:
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping:
I won't suggest the way to it in a loop because that's already done, but I'd suggest a Streams solution, in a unique line :
Map<String, Double> alldataMap = new HashMap<>();
try {
alldataMap =
Files.lines(Paths.get("", filepath))
.map(str -> str.split(cvsSplitBy))
.filter(splitte -> !splitte[0].equals("Voertuig"))
.collect(Collectors.toMap(sp -> sp[0],
sp -> Double.parseDouble(sp[8].replaceAll(",", ".")),
(i1, i2) -> i1 + i2));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(alldataMap); // {Apples=4212.0, Bananas=985.23}
The steps are the same :
Iterate over the lines
split on the cvsSplitBy
remove lines which starts with Voertuig (! use .equals() and not !=)
build the map following 3 rules :
the key is the first String
the value is second String parsed as Double
if merge is required : sum both
Edit, as nobody propose the use of .getOrDefault() I give it
while ((line = br.readLine()) != null) {
String[] splitter = line.split(cvsSplitBy);
if (!splitter[0].equals("Voertuig")) {
alldataMap.put(splitter[0],
alldataMap.getOrDefault(splitter[0], 0.0) +
Double.parseDouble(splitter[8].replaceAll(",", ".")));
}
}
If tke key already exists, it'll sum, it the key does not exists it'll sum the value with a 0
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a button which gets a list of files into an array then calls a WwritefiletoDB function for each file:
private void BtnImportActionPerformed(java.awt.event.ActionEvent evt) {
// Create array to store filenames
List<String> filenames = new ArrayList<String>();
JTextFiles.append("*** Current Files Processing ***\n");
File dir = new File(TextFieldDirectory.getText());
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".pdf");
}
});
for (File file : files) {
if (file.isFile()) {
JTextFiles.append(file.getAbsolutePath() + "\n");
try {
writefiletoDB(file.getAbsolutePath());
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JTextFiles.append("*** Finished Processing ***\n");
}
Note the try catchblocks.
The writefiletoDB method has this code:
public void writefiletoDB(String currentfile) throws SQLException, IOException {
//System.out.println("This is current file:" + currentfile);
PDDocument pdfDocument = PDDocument.load(new File(currentfile));
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();
List fields = acroForm.getFields();
PDField EventNo = acroForm.getField("EventNo");
System.out.println("Event String Length: " + EventNo.getValueAsString().length());
// If event number too short - then skip record
if (EventNo.getValueAsString().length() != 10) {
//JOptionPane.showMessageDialog(null, currentfile +" record was skipped - invalid EventNo = " +EventNo.getValueAsString());
JTextFiles.append("The above file skipped - the event number was incorrect length\n");
pdfDocument.close();
return;
};
Iterator fieldsIter = fields.iterator();
// Create Hashmap "pdf" storing PDF field names & values
Map<String, String> pdf = new HashMap<String, String>();
while (fieldsIter.hasNext()) {
PDField field = (PDField) fieldsIter.next();
// Next line removes braces for dropdowns and any leading whitespace
pdf.put(field.getPartialName(), field.getValueAsString().replaceAll("[\\[\\]]", "").trim());
}
//Create list "columns" to store field names from Database
List<String> columns = new ArrayList<String>();
Connection conn = null;
Statement stmnt = null;
try {
//Connect to DB
conn = DriverManager.getConnection("jdbc:ucanaccess://" + TextFieldDatabase.getText());
stmnt = conn.createStatement();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "A SQL Error: " +se, "SQL ERROR", JOptionPane.ERROR_MESSAGE);
return;
}
// Check If Event Number already exists in DB - if so then exit
System.out.println("Checking if event exists");
PreparedStatement psEvent = conn.prepareStatement("SELECT EventNo FROM test WHERE EventNo = ?");
psEvent.setString(1, EventNo.getValueAsString());
ResultSet rsEvent = psEvent.executeQuery();
if (!rsEvent.next()) {
System.out.println("Result set is empty");
} else {
JTextFiles.append("The above record already exists - skipping\n");
pdfDocument.close();
return;
}
// Get a list of column names from database
ResultSet rs = stmnt.executeQuery("SELECT * FROM test WHERE False");
ResultSetMetaData rsmd = rs.getMetaData();
//System.out.println("Column names as reported by ResultSetMetaData:");
// Add the column names from database to List columns
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println(rsmd.getColumnName(i));
// Store the column names from DB in list columns (via result set rsmd)
columns.add(rsmd.getColumnName(i));
}
// col and val strings to be built colname,colname and ?,?,?,? etc
// for sql prepared statement into DB
StringBuilder col = new StringBuilder();
StringBuilder val = new StringBuilder();
String separator = "";
for (String c : columns) {
if (pdf.containsKey(c)) {
col.append(separator).append(c);
val.append(separator).append("?");
separator = ",";
}
}
// Insert into DB SQL Statement
String sql = String.format("INSERT INTO test (%s) VALUES (%s)", col.toString(), val.toString());
System.out.println(
"This is sql statement: " + sql);
try (PreparedStatement insert = conn.prepareStatement(sql)) {
//Insert position in statement
int pos = 0;
//Second iterations: Bind the values to the statement *** colums is names of cols fromDB
for (String c : columns) {
//Your PDF has a matching formfield ** pdf is hashmap <string,string>
if (c.toLowerCase().contains("date")) {
System.out.println("A Date field has been found: " +c);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy kk:mm");
DateTime startdt = formatter.parseDateTime(pdf.get("DateStart") +" " +pdf.get("TimeStart"));
long millis = formatter.parseMillis(pdf.get("DateStart") +" " +pdf.get("TimeStart"));
Timestamp timeStamp = new Timestamp(millis);
insert.setTimestamp(++pos, timeStamp);
}
if (pdf.containsKey(c) && !c.toLowerCase().contains("date")) {
insert.setString(++pos, pdf.get(c));
}
}
insert.executeUpdate();
} catch (SQLException e) {
//JFrame frame;
JOptionPane.showMessageDialog(null, "A SQL Error: " +e, "SQL ERROR", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
pdfDocument.close();
}
Note the try catch block, about line 30. If it generates a error the return statement breaks and it returns to the calling method BtnImportActionPerformed and that loops calls the next file generating another error.
I need a way to break out of both writefiletoDB and also stop BtnImportActionPreformed.
Is there a way to handle writefiletoDB exceptions in BtnImportActionPreformed? or break out of both.
What is the best way to do this - I want to make the code more robust.
Thanks
Al
Simplifying your example to the relevant structure, the code is doing this:
void BtnImportActionPerformed() {
for(int i = 0l i < 10; i++) {
writefiletoDB();
}
}
void writefiletoDB() {
try {
doSomething();
} catch (SomeException e) {
return;
}
}
Since the exception is being caught and handled in the inner method, there's no way for the outer method to know that anything went wrong. If you want the outer method to know that an exception has occurred, use the same pattern as the inner method. Catch a thrown exception. Something like this:
void BtnImportActionPerformed() {
for(int i = 0l i < 10; i++) {
try {
writefiletoDB();
} catch (SomeException e) {
// do anything else?
return;
}
}
}
void writefiletoDB() throws SomeException {
try {
doSomething();
} catch (SomeException e) {
// log it? something else?
throw e;
}
}
You might even be able to skip the inner try/catch entirely if the outer method can do all of the exception handling. You'd simply have to declare the possible exceptions on the writefiletoDB method.
There are multiple ways to solve this, I would choose depending upon what is right for your logic.
Do not catch any exception and let the caller of BtnImportActionPerformed catch.
Put try catch around the for loop of BtnImportActionPerformed that way once exception is raised you are out of the loop. Do remove the try/catch inside the for loop.
From the writefiletoDB return success/failure instead of exception. In BtnImportActionPerformed based on the success/failure you can exit the loop.
So I'm trying to import a CSV file into my MySQL database through my Java program. The program imports everything that's in the file, like it's suppose to, but the first row, it send to the end of the table, and the program see it's there, but if I search for that nr, it says it doesn't exists. And if I go directly to the database table and edit the nr(if the nr is 137, and I edit and write 137 again) the program recognize that nr, and if I search for it, it will find, and the database table organizes itself and sends that entry where is suppose to be.
I just don't see any logic in this. I someone could help me out, I'd appreciated.
LOAD DATA INFILE 'C:\\Users\\carla.DESKTOP-9364K9K\\Desktop\\Alunos_1.csv'
INTO TABLE utentes character set utf8
FIELDS TERMINATED BY ','
(NrProcesso, Nome, #Nome_Resumido, Ano, Turma, #Subsidio, #Nome_EE, #NIF, #email, #Obs)
SET
Subsidio = IF(#Subsidio='','Nenhum',#Subsidio),
Nome_Resumido = IF(#Nome_Resumido='',NULL,#Nome_Resumido),
Nome_EE = IF(#Nome_EE='',NULL,#Nome_EE),
NIF = IF(#NIF = '', NULL,#NIF),
email = IF(#email='',NULL,#email),
Obs = IF(#Obs='',NULL,#Obs);
Thanks in advance.
You have do do something to check cell/column value and form a sql to inject in MySQL.
public List<Object> getRecordingsListFromCsv(String csvFileLocation, String mp3FileLocation, String mp3FileLocation2, String saveFileLocation, ChannelSftp sftp) {
Map<String, File> recordingsFilesMap = null;
BufferedReader br = null;
List<String> errorFilesList = new ArrayList<>();
List<Object> tempList = new LinkedList<>();
try {
csvRows = 0;
recordingsFilesMap = new LinkedHashMap<>();
br = new BufferedReader(new FileReader(csvFileLocation));
String line = br.readLine();
scriptLog.info("\n" + csvFileLocation + " loaded. Parsing File...");
while ((line = br.readLine()) != null) {
String[] csvArray = parseCsvLineToArray(line);
// System.out.println(Arrays.asList(csvArray) + "\n\n");
if (csvArray[0].trim().isEmpty()) {
continue;
}
/* Do your stuff here */
csvRows++;
}
} catch (FileNotFoundException e) {
scriptLog.error("\n---ERROR---\n FILE NOT FOUND: " + csvFileLocation);
String errorStr = "Type=" + e.toString();
errorStr += "StackTrace=" + Arrays.toString(e.getStackTrace());
scriptLog.error(errorStr);
} catch (IOException e) {
String errorStr = "Type=" + e.toString();
errorStr += "StackTrace=" + Arrays.toString(e.getStackTrace());
scriptLog.error(errorStr);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
Hope it will help you at some extent!!
I use dropbox /delta endpoint to track changes inside Dropbox.
More precisely, the following piece of code allow me to track changes in "/superfolder" recursively (I'm using here DbxClientV1):
List<String> listOfResults = new ArrayList<String>();
String path = "/superfolder";
String cursor = null;
while (true) {
DbxDelta<DbxEntry> deltaWithPathPrefix = client.getDeltaWithPathPrefix(cursor, path);
cursor = deltaWithPathPrefix.cursor;
if (deltaWithPathPrefix.reset) {
System.out.println("Reset!");
}
for (DbxDelta.Entry entry : deltaWithPathPrefix.entries) {
if (entry.metadata == null) {
System.out.println("Deleted: " + entry.lcPath);
listOfResults.add(entry.lcPath);
} else {
System.out.println("Added or modified: " + entry.lcPath);
}
}
if (!deltaWithPathPrefix.hasMore) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(MainSearchV1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Now, I've switched to DbxClientV2 client. To track changes on dropbox I use client.files.listFolder() in the following form:
TreeMap<String, Metadata> children = new TreeMap<String, Metadata>();
Files.ListFolderResult result;
String cursor = null;
while (true) {
if (cursor == null) {
result = client.files.listFolder("/superfolder");
} else {
result = client.files.listFolderContinue(cursor);
}
cursor = result.cursor;
for (Metadata md : result.entries) {
if (md instanceof DeletedMetadata) {
children.remove(md.pathLower);
System.out.println("Deleted: " + md.pathLower);
} else {
children.put(md.pathLower, md);
System.out.println("State: " + md.pathLower);
System.out.println(md.toString());
}
}
if (!result.hasMore) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
Regretably, I've discovered that I can only track changes only of "superfolder" folder.
Is there a way to get a "global cursor" that tracks changes recursively in Dropbox API v2?
The Java SDK uses the builder pattern for pretty much all calls with multiple optional arguments. If I understand your question correctly, I think you're looking for this:
result = client.files.listFolderBuilder("/superfolder")
.recursive(true)
.start();
EDIT: You asked about a "global" cursor. I think you actually meant recursive, but in case you really meant global, you can pass an empty string ("") as a path to represent the root.
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 ;-)