Issue with title text in Java - java

I have used Jtidy parser in java to fetch the title text.
String titleText=null;
try {
titleText = doc.getElementsByTagName("title").item(0)
.getFirstChild().getNodeValue();
} catch (Exception e1) {
try {
titleText = doc.getElementsByTagName("title").item(1)
.getFirstChild().getNodeValue();
} catch (Exception e2) {
try {
titleText = doc.getElementsByTagName("title").item(2)
.getFirstChild().getNodeValue();
} cathc (...)
}
}
above code is working fine,It is reading title at 0'th index,if not found then at 1'st index,and then at 2'nd index.But here I am getting issue:-for some page,title text is present at mid of page or below that,so this code is not working for such pages.In this way,for such condition, length of program is getting increased.Is there any other solution,which will read the title from entire page in one go?.Please help me.

I suggest you do it like this:
String titleText=null;
NodeList titles = doc.getElementsByTagName("title");
for (int i = 0; titleText == null && i < titles.getLength(); i++) {
try {
titleText = doc.item(i).getFirstChild().getNodeValue();
} catch (SomeException e) {
}
}

Related

Get all checked value from the table

I'm trying to get all value from a table where the checkbox is checked, I've make codes but it only gets one output and not working if I checked randomly you have to start checking from the start to make it work.
This the Output I need:
this my current codes I've make:
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.setText(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
this codes only display is one value at the text area.
I hope you can help me with this problem.
You can try below.
TableModel model = table_test.getModel();
for(int i=0; i<model.getRowCount();++i)
{
Boolean isChecked = Boolean.valueOf(model.getValueAt(i, 0).toString());
String col = model.getValueAt(i,1).toString();
if (isChecked==true) {
try{
textarea.append(col);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}

Find Text in Microsoft Word And Replace With Java String Array

I am attempting to find the value $beta in my word doc and replace with an array of data from my java program. The data that I want to replace with is
.......
Blue - 33 - 100
Blue - 28 - 75
Blue - 30 - 90
I verify this is accurate by using the print statement in the syntax below. However, when I open my word document after code saves it, ONLY the last value Blue - 30 - 90 is in the word document, not all 3 stacked on each other like I have in my code post above.
Just like my example above this is how I want the code to appear in the word document when replaced with the java syntax. How should the code read to make that happen?
public static void Test() {
String valuetowrite = null;
for (SPData data : qryresults) {
valuetowrite = String.join("\r\n", data.toString());
System.out.println(valuetowrite);
}
try {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(SOURCE_FILE));
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null) {
if (text.contains("$beta")) {
text = text.replace("$beta", valuetowrite);
r.setText(text, 0);
}
}
}
}
}
doc.write(new FileOutputStream(OUTPUT_FILE));
} catch (Exception ex) {
ex.printStackTrace();
}
}
EDIT
I follow code suggestion in the answer and use the below syntax which on the JAVA side of things, has the data print as desired, but once it is in word, all the data is on one line, not each on an individual line like I desire
String valuetowrite = "";
for (SPData data : qryresults) {
valuetowrite = valuetowrite + String.join("\r\n", data.toString());
}
System.out.println(valuetowrite);
Try the code below, it is using r.addBreak(); which will add in a line break like you want.
private static void WriteToWordWithLineBreak() {
ArrayList<String> datatowrite = new ArrayList<String>();
for (SPData data : qryresults) {
datatowrite.add(data.toString());
}
try {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(SOURCE_FILE));
for (XWPFParagraph p : doc.getParagraphs()) {
System.out.println("Found paragraph "+p);
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null) {
if (text.contains("$beta")) {
r.setText(datatowrite.get(0), 0);
for (int i=1; i < datatowrite.size(); i++){
r.addBreak();
r.setText(datatowrite.get(i));
}
}
}
}
}
}
doc.write(new FileOutputStream(OUTPUT_FILE));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Try this:
String valuetowrite = "";
for (SPData data : qryresults) {
valuetowrite = valuetowrite + String.join("\r\n", data.toString());
}
System.out.println(valuetowrite);

Appending text on a character interval

I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}

NullPointerException with listview on android

I am want to show this json data in to listview. Iam having this problem:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
private String[] arrow() throws JSONException {
json = new JSONObject();
JSONArray com= null;
String[] list = new String[10];
try {
com = json.getJSONArray("parameters"); // this have 10 different values
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++)
try {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
I did it with textview but cant do it with listview, i get this nullpointer..
Please help. Thanks.
There are multiple problems. The first problem is that you are using two try/catch. If you get exception in first one, you still go to 2nd try and try to run code.
json = com.getJSONObject(i);
this line is in 2nd try catch. In your case it seems com is null because there was exception in 1st try/catch.
try {
com = json.getJSONArray("parameters"); // this have 10 different values
for (int i = 0; i < com.length(); i++) {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
}
} catch (JSONException e) {
e.printStackTrace();
}

Android - for loop terminating early

I'm trying to manipulate a JSONArray, rawJArr, (taken from the Reddit API), and get the url and a bitmap (taken from the gfycat "API") from each object to create an ArrayList (listing) of Highlight instances which will be converted to a CardView containing a picture, a short description, and a link to the gfycat.
try {
int count = 0;
int highlightMax;
Bitmap bitmap = null;
Highlight curHighlight;
myJSON = new JSONObject(rawJSON);
curJSON = myJSON.getJSONObject("data");
rawJArr = curJSON.getJSONArray("children");
String strHighlightNo = mySPrefs.getString("pref_highlightNo", "notFound");
if(strHighlightNo.equals("notFound")) {
Log.w("FT", "shared pref not found");
return null;
}
highlightMax = Integer.parseInt(strHighlightNo);
Log.w("Arr Length", Integer.toString(rawJArr.length()));
Log.w("Highlight No", Integer.toString(highlightMax));
for(int i=0; i < rawJArr.length(); i++) {
Log.w("Count", Integer.toString(count));
Log.w("I", Integer.toString(i));
if(count == highlightMax) {
Log.w("FT", "Breakpoint reached!");
break;
}
curJSON = rawJArr.getJSONObject(i).getJSONObject("data");
String url = curJSON.getString("url");
String[] parts = url.split("//");
String imageUrl = "http://thumbs." + parts[1] + "-thumb100.jpg";
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
}
// if there is no available picture, then don't include one in the Highlight
if(bitmap == null) {
Log.w("FT", "Null bitmap");
curHighlight = new Highlight(curJSON.getString("title"), url, null);
listing.add(curHighlight);
count++;
} else {
Log.w("FT", "Bitmap Available");
curHighlight = new Highlight(curJSON.getString("title"), url, bitmap);
listing.add(curHighlight);
count++;
}
}
} catch(JSONException e) {
e.printStackTrace();
return listing;
}
However, my for loop terminates way too early. The current JSONArray I'm using has a length of 25, and I've specified a pref_highlightNo of 15, but my for loop terminates after 6 iterations.
My Log.w tests in the for loop all record the same count (Count: 1, Integer: 1 - Count: 6, Integer: 6).
I'm struggling to see why my loop is terminating: there is no stack trace printed to my console, and my app doesn't crash.
Any idea what's going on?
Turns out the issue was specific to the last url I was trying to create to get the required gfycat - I didn't have any code to handle cases where the link began with http://www.

Categories