I want to get a JSON response from a php displayed in a TextView in Android Studio. I now have this code to do that, but it doesn't work. As far as I can see it doesn't even run when the app is opened.
public class MainActivity extends Activity {
private SQLiteHandler db;
private SessionManager session;
private 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();
}
}
public void main(String[] args) throws IOException, JSONException {
TextView txtUser = (TextView) findViewById(R.id.user);
JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
System.out.println(json.toString());
System.out.println(json.getString("saldo"));
try {
JSONObject jsonObject = new JSONObject();
String response = jsonObject.getString("saldo");
txtUser.setText(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
Can anyone see what I'm doing wrong? The response from the url is
{"saldo":783}
.