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}.
Try it!
remove
JSONObject jsonObject = new JSONObject();
And use
JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
try {
String response = json.getString("saldo");
Log.e("AAAAAAAAA %s", response);
}
You must call it in AsyncTask. Completed code!!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
new GetDataSync().execute();
}
String saldo = "";
public class GetDataSync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
txtUser.setText(saldo);
}
}
private void getData() throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
try {
String response = json.getString("saldo");
Log.e("AAAAAAAAA %s", response);
saldo = response;
} catch (JSONException e) {
e.printStackTrace();
}
}
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();
}
}
I think the problem is here in main function in try block
JSONObject jsonObject = new JSONObject();
String response = jsonObject.getString("saldo");
txtUser.setText(response);
your jsonObject is empty You should call
String response = json.getString("saldo");
txtUser.setText(response);
One more thing when you are making some network call you should do it in background thread , not on UI thread.(readJsonFromUrl method should be called in background thread)
as Nguyễn Trung Hiếu's answer suggested
Related
I'm programming an app that calculates, in route, two locations. I've implemented the google places API to get the lat/lon based on name or address but I can't implement the Distance API. The classes/methods don't appear when I try to import. Below is an example of what I'm trying to do.
private static final String API_KEY = "YOUR_API_KEY";
private static final GeoApiContext context = new
GeoApiContext().setApiKey(API_KEY);
public DistanceMatrix estimateRouteTime(DateTime time, Boolean isForCalculateArrivalTime, DirectionsApi.RouteRestriction routeRestriction, LatLng departure, LatLng... arrivals) {
try {
DistanceMatrixApiRequest req = DistanceMatrixApi.newRequest(context);
if (isForCalculateArrivalTime) {
req.departureTime(time);
} else {
req.arrivalTime(time);
}
if (routeRestriction == null) {
routeRestriction = DirectionsApi.RouteRestriction.TOLLS;
}
DistanceMatrix trix = req.origins(departure)
.destinations(arrivals)
.mode(TravelMode.DRIVING)
.avoid(routeRestriction)
.language("fr-FR")
.await();
return trix;
} catch (ApiException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
The GeoApiContext and DistanceMatrix don't appear at import.
Tks for help.
Answering my question...
public class GetJson extends AsyncTask<Void, Void, DeliveryData> {
#Override
protected void onPreExecute() {
// progressDialog
}
#Override
protected DeliveryData doInBackground(Void... params) {
Utils util = new Utils();
DeliveryData json = util.getInfo("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins="+latLngCompany.latitude+","+latLngCompany.longitude+
"&destinations="+latPlace+","+lonPlace+"&key=" + APISERVERKEY);
deliveryData.saveDeliveryData();
return json;
}
#Override
protected void onPostExecute(DeliveryData deliveryData) {
//progressDialog.dismiss
}
}
Created a AsyncTask to get json from url with the especifics parameters.
public class Utils {
public DeliveryData getInfo(String end){
String json;
DeliveryData output;
json = NetworkUtils.getJSONFromAPI(end);
output = parseJson(json);
return output;
}
private DeliveryData parseJson(String json){
try {
DeliveryData deliveryData = new DeliveryData();
JSONObject distanceJson = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0)
.getJSONObject("distance");
Double distanceDouble = null ;
String distance = distanceJson.get("text").toString();
if (distance.contains("km")){
distanceDouble = Double.parseDouble(distance.replace("km", ""));
}else {
distanceDouble = Double.parseDouble("0." + distance.replace("m", ""));
}
deliveryData.setDistance(distanceDouble);
return deliveryData;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
}
At getInfo, the data from url is passed to string. Then, parseJson is call to transform the string to JsonObject.
My Json there is only one position. So, the object is selected at array and the String is parse to Double, excluding the chars. In the end, the distance is saved at object.
public class NetworkUtils {
public static String getJSONFromAPI (String url){
String output = "";
try {
URL apiEnd = new URL(url);
int responseCode;
HttpURLConnection connection;
InputStream is;
connection = (HttpURLConnection) apiEnd.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.connect();
responseCode = connection.getResponseCode();
if(responseCode < HttpURLConnection.HTTP_BAD_REQUEST){
is = connection.getInputStream();
}else {
is = connection.getErrorStream();
}
output = convertISToString(is);
is.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
private static String convertISToString(InputStream is){
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br;
String row;
br = new BufferedReader(new InputStreamReader(is));
while ((row = br.readLine())!= null){
buffer.append(row);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
This class is resposible for connecting to server and get the data from url.
I don't know where exactly the problem lies, the app crashes anytime I log.i the info from the api.
This is the code. I don't know whether the code is out dated, I am running the newest version of Android Studio.
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
Log.i("description", jsonPart.getString("description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
If you could help me out that would be awesome, I'm quite excited to make my own weather app!
You don't convert a single byte and convert to a char like this:
char current = (char) data;
Your result string will end up with lots of strange characters
Instead you wrap your InputStreamReader to a BufferedReader, read line by line and collect your JSON.
Another easier way is to use JSONObject to read your stream:
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
Then change your AsyncTask to return JSONObject directly
public class DownloadTask extends AsyncTask<String, Void, JSONObject> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in, "UTF-8");
JSONParser jsonParser = new JSONParser();
return (JSONObject)jsonParser.parse(reader);;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
}
}
I am having an error in the method that retrieves the JSONObject and converts it to a string, the error says "!DOCTYPE of type java.lang.String cannot be converted to JSONObject"
public class FindSentimentTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String toReturn= "DID NOT WORK";
try
{
toReturn=getResponseFromHttpUrl(url[0]);
}catch (Exception e)
{
Log.d("ErrorInApp","exception on get Response from HTTP call" + e.getMessage());
return toReturn;
}
return toReturn;
}
protected void onPostExecute(String sentimentData) {
try {
JSONObject sentimentJSON = new JSONObject(sentimentData);
((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());
//String testOutput = sentimentJSON.get("docs").toString();
//((TextView)findViewById(R.id.output)).setText(testOutput.toString());
} catch (Exception e) {
Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
}
}
}
public static String getResponseFromHttpUrl(String url) throws IOException {
URL theURL = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) theURL.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
More specificaly the error is here where I retrieve the JSONObject and turn it into a string to display in a TextView
protected void onPostExecute(String sentimentData) {
try {
JSONObject sentimentJSON = new JSONObject(sentimentData);
((TextView)findViewById(R.id.output)).setText(sentimentJSON.toString());
} catch (Exception e) {
Log.d("ErrorInApp","exception in onPostExecute" + e.getMessage());
}
}
The API I am using is https://developer.nytimes.com/article_search_v2.json
I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.
i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)
Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.