PotatoesPower PotatoesPower - 3 months ago 8
Android Question

Get value from JSON and put it in String

it's my first question here, i've try to be the more explicit :)

I want get value from a

JSON
page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.

I have follow a tutorial about
json object
.

But i want get the value
"onair"
and put this in a
String
for use a
IF STRING == "XX"
.

This is my code :

public class notification extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);

detectonline();

}

public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}

*/

}

public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

String jsonText = readFromUrl(channerUrl);// reads text from URL

JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();

return !json.get("onair").isJsonNull();
}

private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}

Answer

I remake your method according what you are looking for it's one of several way to parse json data :

 public static boolean checkIfOnline(String channel) throws JSONException {
    String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";

    String jsonText = readFromUrl(channerUrl);// reads text from URL

    JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
    if(json.has("onair")) { // just a simple test to check the node that you need existe
        boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type 
        return value;
    }
    return false;
}
Comments