My JsonReader class get terminated without printing any output - java

I'm using the following class to read a JSON file on some URL and make a JSONObject from it. When outputting something on the screen the program gets terminated without anything in the console. This is the code:
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
System.out.println("in main!");
JSONObject json = readJsonFromUrl("http://somesubdomain.domain.com/blabla.json");
//System.out.println(json.get("id"));
}
}
It's really weird because it seems it doesn't even go in the main method. I just validated the JSON file and there's nothing wrong with it. Anybody any idea? Thanks.
EDIT: I found out that this works in a project on its own. This happens only when in the main package of the Android project.

Is this an android project? There is no public static void main(...) for android projects. You need to put this in an Activity.

Related

Java Get Link From Another Class (Json)

I have a WebView and I want to get this WebView's link from another class.
My another class gets this link from JSON data. Would you help me please? I am new at Java :/
Main.java;
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
engine.load("https://www.google.com");
}
});
Reader.java (Link is in here)
public class Readerr {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://api.myjson.com/bins/cs3x6");
String Link = json.get("link").toString();
}
}

My java swing timer is limited to a +- 300ms schedule

So I set up an Arduino as a JSON server, which's data I'd then like to log in a .log file on my desktop. The problem however is that the timer (javax.swing.timer) wont't work with any value longer than about +- 300ms. The rest of the code works fine, but maybe the JSON library has some influence on the timer? I'd be glad if someone were to help. The program does execute, and it doesn't show any error when I'm compiling it. This is most of the code, and I've marked the place where I think it fails with some asterisks:
public class ikd {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
getData();
}
public static void getData() throws IOException, JSONException {
//***********************************************
//***********************************************
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("yea");
}
};
new Timer(>+-300 works here but 400 doesn't!!!<, taskPerformer).start();
//***********************************************
//***********************************************
JSONObject json = readJsonFromUrl(">");
System.out.println(json.toString());
JSONArray arr = json.getJSONArray("kamers");
JSONObject tempObj = (JSONObject)arr.get(0);
String temp = tempObj.getString("temp");
String humidity = tempObj.getString("humidity");
String light = tempObj.getString("ldr");
System.out.println("Temperatuur: " + temp + ", Luchtvochtigheid: " + humidity + ", Lichtsterkte: " + light);
try{
PrintWriter writer = new PrintWriter("data.log", "UTF-8");
writer.println(temp + "," + humidity + "," + light);
writer.close();
} catch (Exception e) {
}
}
If I put the timer in the Main() method,nothing happens at all.
This is the console output with the timer running at 301 ms intervals:
301 ms interval:
And this is the console output at a 400 ms interval:
400 ms interval:

android JSON from Url

So I am trying to retrieve JSON object from url.
And I cannot retrieve anything from url.
So to test why, I tried the same code on Spring application, and it works just fine.
It crashes on code below only on android environment.
Please help
package com.example.sandbox;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
Please check your internet connection and also check if you have added permission for INTERNET in your app's manifest that might be issue.
what error do you get exactly ?

gson with mixed read

I'm trying to read json with gson, but I can't get a "simple" gson example to work.
From: https://sites.google.com/site/gson/streaming
public List<Message> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
Message message = gson.fromJson(reader, Message.class);
messages.add(message);
}
reader.endArray();
reader.close();
return messages;
}
Here's the problem, if I try with:
JsonReader reader;
Gson gson = new Gson();
gson.fromJson(reader,Program.class);
It doesn't even build.
The method fromJson(String, Class<T>) in the type Gson is not applicable for the arguments (JsonReader, Class<Program>)
There seems to be a method according to eclipse:
fromJson(JsonReader arg0, Type arg1)
Replace
import android.util.JsonReader;
with
import com.google.gson.stream.JsonReader
did it! =)
It is mentionned that the fromJson method accepts argument 0 as a String. Try to create a method that transforms the inputStream to a String.
static public String generateString(InputStream stream) {
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
try {
String cur;
while ((cur = buffer.readLine()) != null) {
sb.append(cur).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}

reading from a bufferedreader stream globaly

so Im trying to write this class which is going to parse a file and read commands from it.
I want the ctor to just open the stream and do nothing else.
while I parse the file in other class methods.
But I'm getting a nullpointerexception when I try to read the file in the methods I made.
help will be apprecated :D
public class Parser {
private BufferedReader _input;
private String _command;
public Parser(String filename) throws FileNotFoundException {
FileInputStream fstream = new FileInputStream(filename);
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
}
public boolean hasMoreCommands() throws IOException {
String line;
if ( (line = _input.readLine()) != null) {
return true;
} else {
_input.close();
return false;
}
}
public void advance() throws IOException {
String line;
do {
line = _input.readLine().trim();
} while (line.equals("") || line.substring(0,2).equals(COMMENT_SIGN));
String[] splittedLine = line.split(COMMENT_SIGN);
_command = splittedLine[0];
_command = _command.replace(" ", "");
}
my main for testing it + the exception trace
public static void main(String[] args) throws IOException {
Parser input = null;
input = new Parser("D:\\test.asm");
System.out.println( input.hasMoreCommands());
}
Exception in thread "main" java.lang.NullPointerException
at nand6.Parser.hasMoreCommands(Parser.java:40)
at nand6.Parser.main(Parser.java:116)
Have a look at this snippet of code
public Parser(String filename) throws FileNotFoundException {
FileInputStream fstream = new FileInputStream(_filename);
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
}
Change
BufferedReader _input = new BufferedReader(new InputStreamReader(fstream));
to
_input = new BufferedReader(new InputStreamReader(fstream));
Your mistake : You are creating another local variable of type *BufferedReader _input* hence your class level variable is still null resulting in a NullPointerException
You are basically defining a new BufferedReader object called "_input" inside your constructor. You think that after calling the constructor you instantiate "_input" outside the constructor. But you are not, it refers to null. That's why you are getting NullPointerException. Just remove "BufferedReader" in front of "_input" inside your constructor, in order to refer to correct object.

Categories

Resources