How to display openweather map data separately in Android? - java

I am trying to learn Android Async and json data parsing. I am using openweathermap.org API for displaying current weather for a place user type. My application displayed it However, it is not flexible as it is displaying all different details such as weather description, latitude, longitude, Wind Speed , current temperature.. all in a single string so it is not reusable which we should make. Suppose if i want to display the place on google map with current temperature with a map marker, I should be able to get only what i want in this case current temperature and latitude and longitude.
I want these details to display on separate textfields. I am beginner in Android. Please look into my code and suggest me with a solution and guidance.
Here is my JSONWeatherData.java
public class JSONWeatherData {
public static String getData(String weatherJson) throws JSONException {
String jsonResult = "";
try {
JSONObject JsonObject = new JSONObject(weatherJson);
String cod = jsonHelperGetString(JsonObject, "cod");
if(cod != null) {
if (cod.equals("200")) {
jsonResult += jsonHelperGetString(JsonObject, "name") + "\n";
JSONObject sys = jsonHelperGetJSONObject(JsonObject, "sys");
if (sys != null) {
jsonResult += jsonHelperGetString(sys, "country") + "\n";
}
jsonResult += "\n";
JSONObject coord = jsonHelperGetJSONObject(JsonObject, "coord");
if(coord != null){
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
jsonResult += "Lon: " + lon + "\n";
jsonResult += "Lat: " + lat + "\n";
}
jsonResult += "\n";
JSONArray weather = jsonHelperGetJSONArray(JsonObject, "weather");
if(weather != null){
for(int i=0; i<weather.length(); i++){
JSONObject thisWeather = weather.getJSONObject(i);
jsonResult += "Weather " + i + ":\n";
jsonResult += jsonHelperGetString(thisWeather, "main") + "\n";
jsonResult += jsonHelperGetString(thisWeather, "description") + "\n";
jsonResult += "\n";
}
}
JSONObject main = jsonHelperGetJSONObject(JsonObject, "main");
if(main != null){
jsonResult += "temp: " + jsonHelperGetString(main, "temp") + "\n";
jsonResult += "\n";
}
JSONObject wind = jsonHelperGetJSONObject(JsonObject, "wind");
if(wind != null){
jsonResult += "Wind Speed: " + jsonHelperGetString(wind, "speed") + "\n";
jsonResult += "\n";
}
}
else if(cod.equals("404")){
String message = jsonHelperGetString(JsonObject, "message");
jsonResult += "cod 404: " + message;
}
} else{
jsonResult += "cod == null\n";
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage(), e);
jsonResult += e.getMessage();
}
return jsonResult;
}
private static String jsonHelperGetString(JSONObject obj, String k){
String v = null;
try {
v = obj.getString(k);
} catch (JSONException e) {
e.printStackTrace();
}
return v;
}
private static JSONObject jsonHelperGetJSONObject(JSONObject obj, String k){
JSONObject o = null;
try {
o = obj.getJSONObject(k);
} catch (JSONException e) {
e.printStackTrace();
}
return o;
}
private static JSONArray jsonHelperGetJSONArray(JSONObject obj, String k){
JSONArray a = null;
try {
a = obj.getJSONArray(k);
} catch (JSONException e) {
e.printStackTrace();
}
return a;
}
}
Main Activity
Public class MainActivity extends Activity {
Button btnSubmitCity, btnMap;
EditText editCityText;
TextView weather_description, current_temp, wind_speed, textViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editCityText = (EditText) findViewById(R.id.editCity);
btnMap =(Button) findViewById(R.id.mapButton);
btnSubmitCity = (Button) findViewById(R.id.submitCity);
weather_description = (TextView) findViewById(R.id.weatherDescription);
current_temp = (TextView) findViewById(R.id.currentTemp);
wind_speed = (TextView) findViewById(R.id.windSpeed);
//textViewResult = (TextView)findViewById(R.id.result);
textViewResult = (TextView)findViewById(R.id.result);
btnMap.setVisibility(View.INVISIBLE);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnSubmitCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//editCityText.getText().toString();
//HttpGetTask
String cityString = editCityText.getText().toString();
if(TextUtils.isEmpty(cityString)) {
Toast.makeText(MainActivity.this, "Enter a place", Toast.LENGTH_LONG).show();
return;
} else{
new HttpGetTask(cityString, weather_description).execute(cityString);
btnMap.setVisibility(View.VISIBLE);
}
//String cityString = city.getText().toString();
//new HttpGetTask().execute();
/*
new HttpGetTask(
editCityText.getText().toString(),
textViewResult).execute();
*/
}
});
}
private class HttpGetTask extends AsyncTask<String, Void, String> {
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/weather?";
private static final String TAG = "HttpGetTask";
String cityName;
TextView tvResult;
HttpGetTask(String cityName, TextView tvResult){
this.cityName = cityName;
this.tvResult = tvResult;
}
#Override
protected String doInBackground(String... params){
InputStream in = null;
HttpURLConnection httpUrlConnection = null;
String result = "";
try {
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter("q", cityName+",us") // city
.appendQueryParameter("mode", "json") // json format as result
.appendQueryParameter("units", "imperial") // metric unit
.appendQueryParameter("APPID", "Replace with your openweathermap API ID")
.build();
URL url = new URL(builtUri.toString());
httpUrlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(
httpUrlConnection.getInputStream());
String data = readStream(in);
result = edu.uco.rawal.p6rabina.JSONWeatherData.getData(data);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
if (null != httpUrlConnection) {
httpUrlConnection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
if (result == null || result == "") {
Toast.makeText(MainActivity.this,
"Invalid weather data. Possibly a wrong query",
Toast.LENGTH_SHORT).show();
return;
} else {
//btnMap.setVisibility(View.VISIBLE);
tvResult.setText(result);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer data = new StringBuffer("");
try {
reader = new BufferedReader(new InputStreamReader(in));
String line ;
while ((line = reader.readLine()) != null) {
data.append(line);
}
} catch (IOException e) {
Log.e(TAG, "IOException");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return data.toString();
}
}
}
This code runs and output current weather but its not reusuable because everything is concatenated to single string.

To make it reusable and easy to access to each attribute as you want, how about making a class Weather that contains those attribute and when you start parsing the json, make an instance of it and write them there.
For example, instead of just this:
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
jsonResult += "Lon: " + lon + "\n";
jsonResult += "Lat: " + lat + "\n";
...
change to sth like:
Weather aWeather = new Weather();
String lon = jsonHelperGetString(coord, "lon");
String lat = jsonHelperGetString(coord, "lat");
aWeather.lon = long;
aWeather.lat = lat;
...
return aWeather;
Remember to change return type onPostExcute(String string) into onPostExcute(Weather weather);

Related

Is it possible that the array map is too little for contain about 2000 items?

In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.show();
}
#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 + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.

Global Variable returning to 0.0 after completion of an AsyncTask

The main part of this question is, when I run this code, the TextViews latitudeTextView and longitudeTextView get updated correctly, therefore the global variable are being change to the correct values. But when i try to access them again after going an asynctask, they are set to 0.0, 0.0? Shouldn't they stay as the same values after onPostExecute ends?
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Weather>{
private static final String GOOGLE_CONVERTER = "https://maps.googleapis.com/maps/api/geocode/json";
private static final String GOOGLE_KEY = "AIzaSyBtt8yaXoRvLTkJHUXrhl5pQaLxomReHIA";
public static final int LOADER_ID = 0;
String jsonResponse = "";
private String address;
private TextView latitudeTextView;
private TextView longitudeTextView;
private TextView summaryTextView;
private TextView tempuratureTextView;
private TextView timezoneTextView;
private TextView textTextView;
private double latitude = 0.0;
private double longitude = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = (TextView) findViewById(R.id.latitude);
longitudeTextView = (TextView) findViewById(R.id.longitude);
summaryTextView = (TextView) findViewById(R.id.summaryTextView);
tempuratureTextView = (TextView) findViewById(R.id.temperatureTextView);
timezoneTextView = (TextView) findViewById(R.id.timezoneTextView);
textTextView = (TextView) findViewById(R.id.test);
final EditText addressEditText = (EditText) findViewById(R.id.edittext_address);
Button submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
address = addressEditText.getText().toString().trim();
address = "5121+Paddock+Court+Antioch+Ca+94531";
String fullUrl = GOOGLE_CONVERTER + "?address=" + address + "&key=" + GOOGLE_KEY;
new getlongAndLat().execute(fullUrl);
textTextView.setText(latitude + "");
//Log.e("TAG", latitude + " " + longitude);
// getLoaderManager().initLoader(LOADER_ID, null, MainActivity.this);
}
});
}
#Override
public android.content.Loader<Weather> onCreateLoader(int id, Bundle args) {
return new WeatherAsyncTaskLoader(this, latitude, longitude);
}
#Override
public void onLoadFinished(android.content.Loader<Weather> loader, Weather data) {
}
#Override
public void onLoaderReset(android.content.Loader<Weather> loader) {
}
public class getlongAndLat extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
Log.e("TAG", connection.getResponseCode() + "");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
//trouble closing input stream
e.printStackTrace();
}
}
}
extractJsonResponse(jsonResponse);
return null;
}
#Override
protected void onPostExecute(String s) {
latitudeTextView.setText(latitude + "");
longitudeTextView.setText(longitude + "");
super.onPostExecute(s);
}
}
private void extractJsonResponse(String jsonResponse) {
try {
JSONObject rootJsonObject = new JSONObject(jsonResponse);
JSONArray nodeResultsArray = rootJsonObject.getJSONArray("results");
JSONObject nodeFirstObject = nodeResultsArray.getJSONObject(0);
JSONObject nodeGeometryObject = nodeFirstObject.getJSONObject("geometry");
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
} catch (JSONException e) {
e.printStackTrace();
}
}
private String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
In your code doInBackground(), you are calling extractJsonResponse() method before return statement. In extractJsonResponse(), you are getting lat and long and setting those to Global variables as mentioned in your code
JSONObject nodeLocation = nodeGeometryObject.getJSONObject("location");
latitude = nodeLocation.getDouble("lat");
longitude = nodeLocation.getDouble("lng");
I am sure that you are getting those zero values from Json object. You need to verify this thing at your end

Android Geocoder

In my android application I do reverse Geocode (address from latitude and longitude) . My layout display 9 addresses from Geocoder, but sometimes from start activity to display adresses it takes 15 seconds. How to make it faster? Here is my one method (one of nine) to get one address:
public void aktualizujRynek() {
Thread thread1 = new Thread(new Runnable() {
public void run() {
HttpURLConnection connection = null;
try {
URL myUrl = new URL("http://......http request....................");
connection = (HttpURLConnection) myUrl.openConnection();
InputStream iStream = connection.getInputStream();
final String fResponse = IOUtils.toString(iStream);
final TextView fView = (TextView) findViewById(R.id.button8);
fView.post(new Runnable() {
#Override
public void run() {
// fView.setText("RESPONSE" + fResponse);
}
});
final boolean post = fView.post(new Runnable() {
#Override
public void run() {
//parse
JSONObject root = null;
try {
root = new JSONObject(fResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
//Lat Lon
String Lat = root.getString("Lat");
double Lat_double = Double.parseDouble(Lat);
String Lon = root.getString("Lon");
double Lon_double = Double.parseDouble(Lon);
//not current measurement
String epoch_czujnik = root.getString("Epoch");
long epoch_czujnik_long = Long.parseLong(epoch_czujnik); //czas ostatniego odczytu
long epoch = System.currentTimeMillis() / 1000; //current time
long roznica1 = epoch - epoch_czujnik_long;
//lokalizacja ze współrzędnych
Geocoder geocoder;
List < Address > addresses;
geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
addresses = geocoder.getFromLocation(Lat_double, Lon_double, 1);
String address = addresses.get(0).getAddressLine(0);
String firstWords = address.substring(0, address.lastIndexOf(" "));
String city = addresses.get(0).getLocality();
//localization
if (roznica1 > 7200) {
String komunikat = "(czujnik nie działa)";
if (city.equals(firstWords)) {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + komunikat);
} else {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + firstWords + System.getProperty("line.separator") + komunikat);
}
} else {
if (city.equals(firstWords)) {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city);
} else {
final TextView fView102 = (TextView) findViewById(R.id.button8);
fView102.setText(city + System.getProperty("line.separator") + firstWords);
}
}
//color
String kolor = root.getString("Color");
TextView test = (TextView) findViewById(R.id.button8);
if (roznica1 > 7200) {
test.setBackgroundColor(Color.parseColor("#b3b3b3"));
} else {
test.setBackgroundColor(Color.parseColor(kolor));
}
//IJP
String ijp1 = root.getString("IJP");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//end parse
}
});
} catch (MalformedURLException ex) {
Log.e(TAG, "Invalid URL", ex);
} catch (IOException ex) {
Log.e(TAG, "IO / Connection Error", ex);
} finally {
if (connection != null)
connection.disconnect();
}
}
});
thread1.start();
}

Parsing multiple JsonObject and JsonArray

I have some issues with using multiple jsonobjects I want to use "posts" and "attachments" jsonobjects.
but I tried to use the line and another for loop for attachments jsonObject but it doesnt work.
String postInfo = jsonObject.getString("attachments");
My Json looks like this:
{"posts":[
{"title":"Title","content":"Post content"}
]
}
{"attachments":[
{"url":"http://www.something.com"}
]
}
Java code:
public class NewsActivity extends FragmentActivity {
ViewPager viewPager;
int category;
ArrayList titleList;
ArrayList postList;
ArrayList imgList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
Intent i = getIntent();
category=i.getIntExtra("locationInfo",-1);
try {
String encodedCatName = URLEncoder.encode(Integer.toString(category), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://www.something.co/api/get_category_posts/?id=" + encodedCatName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG);
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
postList = new ArrayList();
titleList = new ArrayList();
imgList = new ArrayList();
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 (Exception e) {
Toast.makeText(getApplicationContext(), "Could not find", Toast.LENGTH_LONG);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String postInfo = jsonObject.getString("posts");
Log.i("Content", postInfo);
JSONArray arr = new JSONArray(postInfo);
JSONArray attachments = jsonObject.getJSONArray("attachments");
for(int i=0; i< attachments.length(); i++){
String url = "";
url = attachments.getJSONObject(i).getString("url");
imgList.add(url);
}
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String title = "";
String post = "";
title = jsonPart.getString("title");
post = jsonPart.getString("content");
if (title != "" && post != "") {
message += title + ": " + post + "\r\n";
titleList.add(title);
postList.add(post);
}
}
viewPager = (ViewPager) findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager(),category,titleList,postList,imgList);
viewPager.setAdapter(swipeAdapter);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find ", Toast.LENGTH_LONG);
}
}
}
}
The type related to 'attachments' is an array, therefore you should call something like:
JSONArray attachments = jsonObject.getJSONArray("attachments")
for(int i=0; i< attachments.length(); i++){
attachments.getJSONObject(i).getString("url");
}

Trying to troubleshoot a JSON with an array within an array

I'm trying to troubleshoot my code, which has a array within an array, and then I want to retrieve all of the ID values inside it
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
String Booked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/Ekko/");
}
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();
JSONArray jsonarray = new JSONArray(finalJson);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
} 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);
ChampionNameInLowerCase = ChampionName.toLowerCase().replaceAll("'", "");;
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameInLowerCase+"_square_0", null ,null);
imgtest.setImageResource(id);
}
}
}
And then more closely the code up for question is this section;
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
When the code directly above is added, it gives an error
org.json.JSONException: No value for id
When I delete that small snippet of code, the code produces
The problem is here Booked = finalObject2.getString("id"); use Booked = finalObject2.getInt("id");
and by the way you can use
JSONObject finalObject2 = jsonarray.getJSONObject(jsonarray2.length()-1); instead the the for (int j=0;j<jsonarray2.length();j++)
In the for-loop where you iterate over jsonarray2 you access jsonarray instead of jsonarray2 to get your JSONObject.

Categories

Resources