JSON retriving data from HttpURLConnection - java

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.

Related

Sorting the json file

Hi I am working on a project it will show USD EUR TRY Bitcoin Gold values i have api for all of this values in json i want to sort them out my json link is this https://canlidoviz.com/doviz-kurlari.jsonld
I am parsing the json with this class
public class ClassJSONParser {
private InputStream is = null;
private JSONObject jObj = null;
private String json = "";
public ClassJSONParser(){
}
public JSONObject getJSONFromURL(String url) {
try {
URL urlObject = new java.net.URL(url);
HttpURLConnection conn=(HttpURLConnection) urlObject.openConnection();
conn.setRequestMethod("GET");
is = new BufferedInputStream(conn.getInputStream());
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
String tmp = line + "/n";
sb.append(tmp);
}
is.close();
json=sb.toString();
}catch (Exception e){
Log.i("Buffer Error","Error Converting Result"+e.toString());
}
try {
if(json !=null){
jObj=new JSONObject(json);
}else{
jObj=null;
}
}catch (JSONException e){
}
return jObj;
}
}
and getting a string like this
ClassJSONParser jParser = new ClassJSONParser();
String url = "https://canlidoviz.com/doviz-kurlari.jsonld";
jsonO= jParser.getJSONFromURL(url);
Log.d("***",jsonO.toString());
what method should i use how can i do can you give me guidance

Not receiving any data from OpenWeatherMap api android studio

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) {
}
}

JSON Parsing to multiple TextView [duplicate]

This question already has answers here:
Asynctask: pass two or more values from doInBackground to onPostExecute
(5 answers)
Closed 5 years ago.
I have problem with parsing my JSON Object to multiple textview.
I have a TextView1, TextView2 and TextView3.
I would like to download data from: "max", "min" and "average" and synch data with .settext in TextView1, TextView2 and TextView3
My JSON looks: {"max":15.6,"min":14.05,"average":14.55}
My code below:
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();
Log.d("Login attempt", connection.toString());
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);
String maxPrice = parentObject.getString("max");
return maxPrice;
} 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;
}
onPostExecute:
protected void onPostExecute (String result){
super.onPostExecute(result);
maxPrice.setText(result);
I can't add more String and synch in other TextView. That's work only for one TextView. I can't synch multiple TextView. Can you help me?
1) Return your finalJson from doInBackground
2) getString & setText in onPostExecute
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
String minPrice = parentObject.getString("min");
String avg = parentObject.getString("average");
tvMaxPrice.setText(maxPrice);
tvMinPrice.setText(minPrice);
tvAvg.setText(avg);
you have two option.
1st option
return your whole json string like
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
return finalJson;
then process your json on your onPostExecute like
protected void onPostExecute (String result){
super.onPostExecute(result);
JSONObject parentObject = new JSONObject(result);
String maxPrice = parentObject.getString("max");
maxPrice.setText(result);
String minPrice = parentObject.getString("min");
minPrice.setText(result);
String avgPrice = parentObject.getString("avg");
avgPrice.setText(result);
}
or
2nd option is
You have to try like this
String result = "";
String maxPrice = parentObject.getString("max");
String avgPrice = parentObject.getString("avg");
String minPrice = parentObject.getString("min");
result = maxPrice+","+avgPrice+","+minPrice;
return result;
then split it on your onPostExecute
protected void onPostExecute (String result){
super.onPostExecute(result);
String[] separated = result.split(",");
maxPrice.setText(separated[0]);
minPrice.setText(separated[2]);
avgPrice.setText(separated[1]);
}

Get JSON data from php to ArrayList of String android

I have built a php script who give me my JSON data of my mysql database, but in android studio I don't know how I can put my data in a ArrayList of String
I have tested many possibilities but no one works,
If you have any idea about my code it can be very good
ArrayList<String> ListeFamilles = new ArrayList<>(15);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectionneracteactivity);
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://192.168.1.26:8888/GetNomFamille.php");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
ListeFamille.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
JSON:
[{"Famille":"TEXT1"},{"Famille":"TEXT2"},{"Famille":"TEXT3"},{"Famille":"TEXT4"},{"Famille":"TEXT5"},{"Famille":"TEXT6"},{"Famille":"TEXT7"},{"Famille":"TEXT8"},{"Famille":"TEXT9"},{"Famille":"TEXT10"},{"Famille":"TEXT11"},{"Famille":"TEXT12"},{"Famille":"TEXT13"},{"Famille":"TEXT14"},{"Famille":"TEXT15"}]
PHP:
<?php
mysql_connect("localhost","root","password");
mysql_select_db("mydb");
$sql=mysql_query("SELECT Famille FROM FAMILLES");
$rows = array();
while($r=mysql_fetch_assoc($sql)){
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
?>
You should not do network connection in mainthread, Read this article and try to add it in asynctask,
For Json parsing after getting the value you can try this,
StringBuilder result = new StringBuilder();
ArrayList<String> listOfValues = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(result.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if(jsonObject == null) {
continue;
}
String jsonValue = jsonObject.optString("Famille");
listOfValues.add(jsonValue);
}
} catch (JSONException e) {
e.printStackTrace();
}

android set data in external database

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.

Categories