Im using Rest Countries API to retrieve language data, https://restcountries.eu/rest/v2/all.. but the languages does't show up because the data was in array.
this is the code that i write to retrieve the data using Method.Get
private void getCountriesList() {
String url = "https://restcountries.eu/rest/v2/all";
StringRequest request = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(!response.isEmpty()) {
Gson gson = new Gson();
JSONObject json = null;
// array of country
LanguageModel[] countries = gson.fromJson(response, LanguageModel[].class);
// add it to adapter
for(LanguageModel country: countries) {
mAdapter.addItem(country);
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getLocalizedMessage());
}
}
);
Volley.newRequestQueue(getApplicationContext()).add(request);
}
This is the model. the code was successful when i retrieve country name, but it was failed when i retrieve language data
public class CountryModel {
private String languages;
public String getLanguages() {
return languages;
}
public void setLanguages(String languages) {
this.languages = languages;
}}
I got it working with the following code:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
for (int i = 0; i < mainArray.length(); i++) {
JSONObject countryObj = mainArray.getJSONObject(i);
JSONArray languageArray = countryObj.getJSONArray("languages");
List<LanguageModel> languageModels = gson.fromJson(languageArray.toString(), new TypeToken<List<LanguageModel>>() {
}.getType());
// add it to adapter
for (LanguageModel languageModel : languageModels) {
//mAdapter.addItem(country);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// array of country
}
Let me know if you still get the error.
Edit:
but how to get country name and language at the same time?
You have to edit your CountryModel as following:
public class CountryModel {
#SerializedName("name")
String countryName;
#SerializedName("languages")
ArrayList<LanguageModel> languages;
public CountryModel() {
}
}
And LanguageModel as following:
class LanguageModel {
#SerializedName("iso639_1")
String iso1;
#SerializedName("iso639_2")
String iso2;
#SerializedName("name")
String name;
#SerializedName("nativeName")
String nativeName;
public LanguageModel() {
}
}
Now the final change in parsing:
if (!response.isEmpty()) {
Gson gson = new Gson();
try {
JSONArray mainArray = new JSONArray(response);
List<CountryModel> countryList = gson.fromJson(mainArray.toString(), new TypeToken<List<CountryModel>>() {
}.getType());
//do something with your country list
Log.d("R-Countries", countryList.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
While this answer works you should see the following link to understand what i did here.
http://www.studytrails.com/java/json/java-google-json-introduction/
Related
I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
Here's the JSON I'm parsing.
<item>{\"name\":{\"mainName\":\"Ham and cheese
sandwich\",\"alsoKnownAs\":[]},\"placeOfOrigin\":\"\",\"description\":\"A ham and cheese
sandwich is a common type of sandwich. It is made by putting cheese and sliced ham
between two slices of bread. The bread is sometimes buttered and/or toasted. Vegetables
like lettuce, tomato, onion or pickle slices can also be included. Various kinds of
mustard and mayonnaise are also
common.\",\"image\":\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/50/Grilled_ham_and_cheese_014.JPG/800px-Grilled_ham_and_cheese_014.JPG\",\
"ingredients\":[\"Sliced
bread\",\"Cheese\",\"Ham\"]}
alsoKnownAs and ingredients arrays don't have keys. I need to convert them to lists and add them to the Sandwich object. Currently, it doesn't work. I thought the code inside the for loop would be enough. Can someone please take a look? Thank you in advance.
I based my code on the answers in this thread: Converting JSONarray to ArrayList
Also, one of the posters in the above thread suggested using a helper method from this link(line 45).
https://gist.github.com/codebutler/2339666
My code:
public static Sandwich parseSandwichJson(String json) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(json)) {
return null;
}
Sandwich sandwiches = null;
try {
// Create a JSONObject from the JSON file
JSONObject jsonObject = new JSONObject(json);
//fetch JSONObject named name
JSONObject objectName = jsonObject.getJSONObject("name");
// Extract the value for the key called "main_name"
String mainName = "";
if (objectName.has("mainName")) {
mainName = objectName.optString(KEY_MAIN_NAME);
}
JSONArray alsoKnownAsArray = objectName.optJSONArray(KEY_ALSO_KNOWN_AS);
List<String> alsoKnownData = new ArrayList();
for (int i = 0; i < alsoKnownAsArray.length(); i++) {
alsoKnownData.add(alsoKnownAsArray.getString(i));
}
String placeOfOrigin = "";
if (objectName.has("placeOfOrigin")) {
placeOfOrigin = objectName.optString(KEY_PLACE_OF_ORIGIN);
}
String description = "";
if (objectName.has("description")) {
description = objectName.optString(KEY_DESCRIPTION);
}
String image = "";
if (objectName.has("image")) {
image = objectName.optString(KEY_IMAGE);
}
JSONArray ingredientsArray = objectName.optJSONArray(KEY_INGREDIENTS);
List<String> ingredientsData = new ArrayList<String>();
if (ingredientsArray != null) {
for (int i = 0; i < ingredientsArray.length(); i++) {
ingredientsData.add(ingredientsArray.getString(i));
}
}
Sandwich sandwich = new Sandwich(mainName, alsoKnownAsArray, placeOfOrigin, description, image, ingredientsArray);
sandwiches.add(sandwich);
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("QueryUtils", "Problem parsing sandwich JSON results", e);
}
// Return the list of sandwiches
return sandwiches;
}
You can parse the JSON this way:
public class JsonUtils {
public static Sandwich parseSandwichJson(String json) {
try {
JSONObject mainJsonObject = new JSONObject(json);
JSONObject name = mainJsonObject.getJSONObject("name");
String mainName = name.getString("mainName");
JSONArray alsoKnownAsArray = name.getJSONArray("alsoKnownAs");
List<String> alsoKnownAs = new ArrayList<>(alsoKnownAsArray.length());
for ( int i = 0; i < alsoKnownAsArray.length(); i++ ) {
alsoKnownAs.add(alsoKnownAsArray.getString(i));
Log.i("alsoKnownAs", "I am here" + alsoKnownAs);
}
String placeOfOrigin = mainJsonObject.optString("placeOfOrigin");
String description = mainJsonObject.getString("description");
String image = mainJsonObject.getString("image");
JSONArray ingredientsArray = mainJsonObject.getJSONArray("ingredients");
List<String> ingredients = new ArrayList<>(ingredientsArray.length());
for ( int i = 0; i < ingredientsArray.length(); i++ ) {
Log.i("ingredients", "These are the ingredients" + ingredients);
ingredients.add(ingredientsArray.getString(i));
}
return new Sandwich(mainName, alsoKnownAs, placeOfOrigin, description, image, ingredients);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Use Gson for parsing (https://github.com/google/gson)
Add this 2 class for data handle
public class CustomData
{
private List<String> ingredients;
private String placeOfOrigin;
private String description;
private Name name;
private String image;
public List<String> getIngredients ()
{
return ingredients;
}
public void setIngredients (List<String> ingredients)
{
this.ingredients = ingredients;
}
public String getPlaceOfOrigin ()
{
return placeOfOrigin;
}
public void setPlaceOfOrigin (String placeOfOrigin)
{
this.placeOfOrigin = placeOfOrigin;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public Name getName ()
{
return name;
}
public void setName (Name name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
}
Class Name:
public class Name
{
private String[] alsoKnownAs;
private String mainName;
public String[] getAlsoKnownAs ()
{
return alsoKnownAs;
}
public void setAlsoKnownAs (String[] alsoKnownAs)
{
this.alsoKnownAs = alsoKnownAs;
}
public String getMainName ()
{
return mainName;
}
public void setMainName (String mainName)
{
this.mainName = mainName;
}
}
Function to parse JSON to Object
public CustomData parseJsonToData(String jsonString) {
CustomData data = new Gson().fromJson(jsonString, CustomData.class);
return data;
}
So you can get List by
CustomData data = parseJsonToData(jsonString)
List<String> ingredients = data.getIngredients()
I'm beginner in Android Studio, and I am a bit difficult to parse json data in Android, so I want to ask question about get or parsing JSON Child Array.
This is my Code :
public void resSuccess(String requestType, JSONObject response)
{ progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONArray array = response.getJSONArray("all_airport");
for (int i=0; i<array.length(); i++){
JSONObject jsonObject = array.getJSONObject(i);
JSONArray jsonArray = jsonObject.getJSONArray("airport");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject object = jsonArray.getJSONObject(j);
BandaraDataSet bds = new BandaraDataSet();
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}
And This is my Json
{
"all_airport":{
"airport":[
{
"airport_name":"Mali",
"airport_code":"ARD",
"location_name":"Alor Island",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Pattimura",
"airport_code":"AMQ",
"location_name":"Ambon",
"country_id":"id",
"country_name":"Indonesia"
},
{
"airport_name":"Tanjung Api",
"airport_code":"VPM",
"location_name":"Ampana",
"country_id":"id",
"country_name":"Indonesia"
}
]
},
"token":"ab4f5e12e794ab09d49526bc75cf0a0139d9d849",
"login":"false"
}
so my problem when Parse Json is null in Android, please help anyone..
You are handling the JSONObject as if it were a JSONArray. Try this code:
public void resSuccess(String requestType, JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
token = response.getString("token");
JSONObject airports = response.getJSONObject("all_airport");
JSONArray airportArray = airports.getJSONArray("airport");
for (int j = 0; j < airportArray.length(); j++) {
BandaraDataSet bds = new BandaraDataSet();
JSONObject object = airportArray.getJSONObject(j);
idDep = object.getString("country_id");
bds.setId(object.getString("id"));
bds.setAirport_name(object.getString("airport_name"));
bds.setAirport_code(object.getString("airport_code"));
bds.setCountry_name(object.getString("country_name"));
bds.setCountry_id(object.getString("country_id"));
bds.setLocation_name(object.getString("location_name"));
list.add(bds);
}
bandaraAdapter = new BandaraAdapter(ActivityPesawat.this, list);
bandaraAdapter.notifyDataSetChanged();
listBandara.setAdapter(bandaraAdapter);
} catch (Exception e){
e.printStackTrace();
}
}
You should proper json parsing or you can use Gson(library) for json parsing. You just need to have proper Model(Bean) classes. And then parsing will be too easy.
compile 'com.google.code.gson:gson:2.7'
Create below Model/Bean classes
import java.io.Serializable;
//Response.java
public class Response implements Serializable {
AllAirPort all_airport;
public AllAirPort getAll_airport() {
return all_airport;
}
public void setAll_airport(AllAirPort all_airport) {
this.all_airport = all_airport;
}
}
//AllAirPort.java
public class AllAirPort implements Serializable{
ArrayList<AirportModel> airport;
public ArrayList<AirportModel> getAirport() {
return airport;
}
public void setAirport(ArrayList<AirportModel> airport) {
this.airport = airport;
}
}
//AirportModel.java
public class AirportModel implements Serializable {
String airport_name;
String airport_code;
String location_name;
String country_id;
String country_name;
public String getAirport_name() {
return airport_name;
}
public void setAirport_name(String airport_name) {
this.airport_name = airport_name;
}
public String getAirport_code() {
return airport_code;
}
public void setAirport_code(String airport_code) {
this.airport_code = airport_code;
}
public String getLocation_name() {
return location_name;
}
public void setLocation_name(String location_name) {
this.location_name = location_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
}
Response responseObject = new Gson().fromJson(yourstringResponse, Response.class);
now you can start getting data from responseObject.
I have json data from webservice that should be stored in two lists, String list and Integer List. the one for strings stores the data fine but the one for the integers doesn't. it prompts error saying java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
here is the complete code
public class Setup extends AppCompatActivity {
Button save;
EditText schoolPK;
String schoolname, classname, cityname, school_id,class_id;
ImageView logout;
GridView grid;
String cityid,classid;
int schoolid;
ArrayList<String> CityName, CityId;
private List<Integer> classID=new ArrayList<Integer>();
private List<String> listschools = new ArrayList<String>();
private List<String> listclasses = new ArrayList<String>();
Spinner schoolspinner;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String classnames = "classname";
public static final String schoolnames = "schoolname";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
String saved_letter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup2);
CityName=new ArrayList<>();
CityId = new ArrayList<>();
//classID = new ArrayList<>();
// schoolID = new ArrayList<>();
schoolPK = (EditText) findViewById(R.id.schoolPK);
final Spinner city = (Spinner) findViewById(R.id.city);
final Spinner classspinner = (Spinner) findViewById(R.id.classname);
String URL_countries="http://192.168.0.148/Election/api/school";
JsonArrayRequest items = new JsonArrayRequest(URL_countries, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0;i<response.length();i++){
try {
JSONObject obj = response.getJSONObject(i);
String country=obj.getString("name_Ar");
String cityid = obj.getString("pK_ID");
CityId.add(cityid);
CityName.add(country);
}
catch (JSONException e) {
e.printStackTrace();
}
city.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, CityName));
}
//to get me the
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder add = new AlertDialog.Builder(Setup.this);
add.setMessage(error.getMessage()).setCancelable(true);
AlertDialog alert = add.create();
alert.setTitle("error");
alert.show();
}
} );
Controller.getInstance(Setup.this).addToRequestque(items);
city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
cityname = parent.getItemAtPosition(position).toString();
cityid = CityId.get(position).toString();
//CityId.clear();
listclasses.clear();
getclasses();
} // to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent) {
}
});
classspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
classname = parent.getItemAtPosition(position).toString();
class_id = classID.get(position).toString();
}
// to close the onItemSelected
public void onNothingSelected(AdapterView<?> parent) {
}
});
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedpreferences = getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
Intent intent = new Intent(getApplicationContext(), Vote.class);
editor.putString("schoolname", cityname);
editor.putString("schoolid", cityid);
editor.putString("classname", classname);
editor.putString("classid", class_id);
editor.apply();
}
});
}
public void getschools(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://192.168.0.148/Election/api/School";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("cityFK_ID", cityid);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<Schoolresponse> list_response = new ArrayList<Schoolresponse>();
Type listType = new TypeToken<List<Schoolresponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
// schoolID= new ArrayList<>();
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
//schoolID.add(listItemData.getId());
listschools.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
schoolspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listschools));
}
});
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
public void getclasses(){
final Spinner classspinner = (Spinner) findViewById(R.id.classname);
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://192.168.0.148/Election/api/classes";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("SchoolFK_ID", cityid);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
classID.add(listItemData.getId());
listclasses.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
and here is the area I'm talking about
where only the string list (listclasses) is storing data while the integer (classID) list does not
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ClassResponse> list_response = new ArrayList<ClassResponse>();
Type listType = new TypeToken<List<ClassResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
School listItemData = new School();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setId(list_response.get(i).getPKID());
classID.add(listItemData.getId());
listclasses.add(listItemData.getName());
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
classspinner.setAdapter(new ArrayAdapter<String>(Setup.this, android.R.layout.select_dialog_item, listclasses));
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
hope I get right answer
thanks in advance
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
means that your Array is empty and you are trying to access array element from an empty array.
You can put a condition to check if array length is more than 0 and then proceed using it like:
if(array != null && array.length > 0){
// do parsing
}
Make sure your class School contains variable with name pK_ID. Look carefully on the upper/lower cases in the variable name.
If the variable name is not matching with JSON tag then this will result in empty fetching from JSON, even if you are getting valid JSON from URL as per your comment.
As you can see in the picture I have JSON object 'multimedia' which has information about picture in 4 different formats. I need url only on of them. Lets say which had standard format (75x75). I use volley library in my android application. I am confused about how to take/parse url (in string format is enough) of image that underlined in the picture.
Here is code that I used:
NewsFragment:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
sendJsonRequest();
}
private void sendJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(10),
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONRequest(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private void parseJSONRequest(JSONObject response){
if(response==null || response.length()==0){
return;
}
try {
JSONArray arrayResult = response.getJSONArray(Keys.EndPointNews.KEY_RESULTS);
for (int i = 0; i < arrayResult.length(); i++){
JSONObject currentResult = arrayResult.getJSONObject(i);
String section = currentResult.getString(Keys.EndPointNews.KEY_SECTION);
String subsection = currentResult.getString(Keys.EndPointNews.KEY_SUBSECTION);
String title = currentResult.getString(Keys.EndPointNews.KEY_TITLE);
String article_abstract = currentResult.getString(Keys.EndPointNews.KEY_ABSTRACT);
String published_date = currentResult.getString(Keys.EndPointNews.KEY_PUBLISHED_DATE);
// HERE IS A PROBLEM: EDIT:
JSONArray arrayMultimedia = currentResult.getJSONArray(Keys.EndPointNews.KEY_MULTIMEDIA);
JSONObject objectMultimedia = arrayMultimedia.getJSONObject(0);
String multimediaURL = null;
if(objectMultimedia.has(Keys.EndPointNews.KEY_MULTIMEDIA_URL))
{
multimediaURL = objectMultimedia.optString(Keys.EndPointNews.KEY_MULTIMEDIA_URL);
}
News news = new News();
news.setSection(section);
news.setSubsection(subsection);
news.setArticleTitle(title);
news.setArticleAbstract(article_abstract);
Date date = mDateFormat.parse(published_date);
news.setPublishedDate(date);
//EDIT
news.setMultimediaURL(multimediaURL);
mListNews.add(news);
}
Toast.makeText(getActivity(),mListNews.toString(),Toast.LENGTH_LONG).show();
}catch (JSONException e){
}
catch (ParseException e) {
e.printStackTrace();
}
}
THANKS FOR ANY HELP!
EDIT:
public String getMultimediaURL(){
return multimediaURL;
}
public void setMultimediaURL(String multimediaURL){
this.multimediaURL = multimediaURL;
}
I must suggest you to go with GSON library for parsing your JSON reposnses. it is very easy, you have to just create your template/entity classes. here is the link and download gson library from here
OR
refer below answer by #ρяσѕρєя K
OR
refer this answer
multimedia is JSONArray instead of JSONObject. get multimedia json array from currentResult JSONObject:
JSONObject currentResult = arrayResult.getJSONObject(i);
JSONArray arrMultimedia = currentResult.getJSONArray(
Keys.EndPointNews.KEY_MULTIMEDIA);
multimedia array contain JSONObejct so get JSONObject from arrMultimedia to get all values using key:
JSONObject jsonObjMultimedia = arrMultimedia.getJSONObject(0);
String strPicUrl=jsonObjMultimedia.optString("url");