Two Json lists in one spinner using else statement - android

In my app I have 2 spinners they are populated with JSON data pulled from a file on my company server.
The spinners are populated if a correct email, password and clientID is entered.
Now I want to add that if the details are wrong or non exist they must show a different JSON.
I am trying to do this by calling an else if statement in my onResponse method.
To summarize
I want each spinner to show a JSON data array with categories/client details in if the login information is entered/correct (this works but I was asked to add this second array for errors) and if there is missing/incorrect information it must show the the JSON array with the errors in. Both JSON arrays are in the same file.
I believe my problem lies with my adapter, as it is calling one ArrayList is it possible to let it call both array lists heres the adapter, I want to add a second ArrayList to this, the current one is "CategoryName"
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
CODE FOR LOADING THE SPINNERS DATA
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String category=jsonObject1.getString("Category");
CategoryName.add(category);
}
}
if (jsonObject.getInt("failed") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("errors");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String error=jsonObject1.getString("reason");
Errors.add(error);
}
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);

You simply have to use your Errors ArrayList. Currently you add the information to it (in your second if branch) but never put it into the spinner.
Try this:
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String category=jsonObject1.getString("Category");
CategoryName.add(category);
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, CategoryName));
}
if (jsonObject.getInt("failed") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("errors");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String error=jsonObject1.getString("reason");
Errors.add(error);
}
spinner.setAdapter(new ArrayAdapter<>(SecondActivity.this, android.R.layout.simple_spinner_dropdown_item, Errors));
}

Related

How to get JSON data out of JSON Array?

I am using the Volley libary to understand working with JSON data, i have successfully retrieved some data and would like to know how to get the individual data out of my json array? I have tried doing what user's suggested on previous stackover flow post but only the json array data is showing up
#Override
public void downloadJson() {
final String url = "https://dog.ceo/api/breeds/image/random/2";
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("message");
Log.i("jsonArray", jsonArray.toString());
for(int i=0; i>jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(getRequest);
}
exactly i can't understand your question .
but in your code there are some problem .
in below you can see my proposal code .
for(int i=0; i<jsonArray.length(); i++)
{
Log.i("obj", jsonArray.get(i).toString());
}
in this code you can get each data from you'r JSONArray and use that URL to load image.
if this is not answer to you'r question i will be glad if you give some explanation about you'r question.
There is mistake in your for loop,
for(int i=0; i<jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
Log.i("obj", object.toString());
}
Hope it will help!!

Android Studio: How to parse a JSON Object from Inside of a JSON Array?

I am trying to parse the following JSON data into a recycler view. In particular, I want to parse the address object to display the locationName, line1, city, state and zip, but I cant get the parsing method right.
{
"pollingLocations": [
{
"address": {
"locationName": "LITTLE LEAGUE HEADQUARTERS",
"line1": "6707 LITTLE LEAGUE DR",
"city": "SAN BERNARDINO",
"state": "CA",
"zip": "92407"
},
"notes": "",
"pollingHours": "07:00-20:00",
"sources": [
{
"name": "Voting Information Project",
"official": true
}
]
}
]
}
My issue is finding the address object. With the current code, I get a logcat error that says No value for locationName. I think this is because I first need to specify the address object to iterate through, but how do I do this? This is the current implementation that I have right now.
//fetch
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("pollingLocations");
for(int i = 0; i < array.length(); i++){
JSONObject addressObject = array.getJSONObject(i);
for (int x = 0; x < addressObject.length(); x++){
VotingLoc votingLoc = new VotingLoc(addressObject.getString("locationName"),
addressObject.getString("line1"),
addressObject.getString("city"),
addressObject.getString("state"),
addressObject.getString("zip"),
addressObject.getString("pollingHours"));
votingList.add(votingLoc);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Locat Error:
Is there an easier way of doing this? I believe the code for my rvadapter class and is correct and the error is in this method, but If you want to see any other code, let me know.
By getting first node in array you have obtained address node so no need to run loop there, address object is not an array you can get values directly. Try something like this:
JSONArray array = object.getJSONArray("pollingLocations");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String locationName = jsonObject.getJSONObject("address")
.getString("locationName");
Log.d("locationName", locationName);
JSONArray sourcesArray = jsonObject.getJSONArray("sources");
// run loop to get values from this array
for (int j = 0; j < sourcesArray.length(); j++){
JSONObject source = sourcesArray.getJSONObject(j);
String name = source.getString("name");
}
}
Another way could be using a json parser like gson (https://github.com/google/gson) or jackson (https://github.com/FasterXML/jackson). This may be a bit overhead if your only goal is to show these few values, as you must create some java classes, you may only need for parsing.

How to receive JSONArray

Following guide I see this:
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("nome_stanza"));
movie.setThumbnailUrl(obj.getString("icona"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController2.getInstance().addToRequestQueue(movieReq); //i need this movieReq
But I don't have a URL where the Jsoncode is collocated, I receive jsoncode from another method that gives me a string like this:
{"risposta_server": [{"nome_stanza":"via oslavia"},{"icona":"http:\/\/****.**.**.**\/fil***\/****\/images\/icon\/icon2.png"},{"Admin":"s"}]}
Then, how can I change the first code to use this result?
I've got mixed up in response, but I understand it's supposed to come Json Object.The next step:
JSONOArray array = response.getJSONArrary("risposta_server");
for (int i = 0; i < array.length(); i++) {
try {
JSONObject obj = array.getJSONObject(i);
Movie movie = new Movie();
if(i == 0){
movie.setTitle(obj.getString("nome_stanza"));
}else if(i == 1){
movie.setThumbnailUrl(obj.getString("icona"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
...
See the job if I misunderstand.
Maybe you need json encode like json_encode($str) on php script. Where $str is an array list.
So, your server script will be like this
$arr = array('hello', 'world', 'where', 'i', 'life');
echo json_encode($arr);
Then you will get json data from server

How can I get a JsonObject from a URL in Android?

I have to a JSONObject, especially the "data" content, in Android from a WebService, then I have to print it into a ListView or a Table.
This is my JSON:
{
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
Let
response = {
"status":200,
"status_message":"Direct ways found",
"data":[{"codice_linea":"5","partenza":"Longa","ora_partenza":"17:34:00","arrivo":"Schiavon","ora_arrivo":"17:38:00"}]
}
String status = response.get("status"); // status = 200
String status_message = response.get("status_message"); // status_message = "Direct ways found"
JSONArray message = response.getJSONArray("data");
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < message.length(); i++) {
HashMap<String, String> hm = new HashMap<String, String>();
JSONObject temp = message.getJSONObject(i);
hm.put("codice_linea",temp.getString("codice_linea"));
hm.put("partenza",temp.getString("partenza"));
hm.put("ora_partenza",temp.getString("ora_partenza"));
hm.put("arrivo",temp.getString("arrivo"));
....................................
.............................
aList.add(hm);
}
Finally all your JSON data is prased to List aList.
Then use custom Listview to show this data in Listview
Here is the full tutorial http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
Hope this solved your problem.
Try this
JSONObject jsonObject = new org.json.JSONObject(YourJsonResponse);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
......
}
I assume you effort to get this Json in android , if i right try this:
Paste your example Json in Json Schema 2 Pojo , and site will generate Pojo classes
Convert your Json response to Pojo class with Gson
Add this line to your dependencies : compile 'com.google.code.gson:gson:2.4'
Convert Json result to Pojo :
Gson gson = new Gson();
YourPojo yourpojo= gson.fromJson(jsonresponse, YourPojo.class);
And handle result whatever you want .
If you didnt effort anything
Go to google and search how to handle Json in android or how to connect web service , for example you can search : HttpUrlConnection , OkHttp, Retrofit ...
What you seem wanting to do is to re-create an existing JSONObject that is contained in an array.
If you use the JSONObject from the Android tools, you can use getJSONObject and getJSONArray.
According to the Documentation:
Returns the value mapped by name if it exists and is a JSONArray, or throws otherwise.
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
See here for more details.
You have to do something like that:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
Your-url-JsonObj, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
// Parsing json object response
// response will be a json object
String status = response.getString("status");
String status_message = response.getString("status_message");
JSONArray jsonArray =jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("codice_linea");
jsonArray.getJSONObject(i).getString("partenza");
jsonArray.getJSONObject(i).getString("ora_partenza");
jsonArray.getJSONObject(i).getString("arrivo");
jsonArray.getJSONObject(i).getString("ora_arrivo");}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}

Parsing JSONArray and showing the data in ListView in android

In my android application I'm receiving a JSONArray and I'm parsing it and storing it in a arraylist and appending that to listview but I'm facing an error entire list is showing in a single list item.but I'm receiving 4 items.This is all what I did.
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("topicsJSON",composeJSON());
client.post("http://www.example.com/load_topics.php",params,newAsyncHttpResponseHandler()
{
public void onSuccess(String response)
{
Gson gson = new GsonBuilder().create();
try
{
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error,String content)
{
if (statusCode == 404)
{
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
else if (statusCode == 500)
{
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]",
Toast.LENGTH_LONG).show();
}
}
});
}
private String composeJSON() {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> check_in_List;
check_in_List = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("subject_code",received_subject_code);
check_in_List.add(map);
Gson gson = new GsonBuilder().create();
return gson.toJson(check_in_List);
}
public void load_data()
{
ArrayAdapter<String> phy = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
l1.setAdapter(phy);
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
String pos = (String) l1.getItemAtPosition(position);
});
}
I'm facing an error entire list is showing in a single list item.but
I'm receiving 4 items
Because calling load_data(); inside for-loop which is used for getting data from JSONArray in ArrayList
Move load_data(); outside for-loop to show each item in separate row in ListView
don't every time add list item, create adapter,
set adapter one time with empty list.
after end parse Jsonarray and add data, adapter.notifyDataSetChanged();
Replace this:
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
load_data();
}
Via
for (int i = 0; i < arr.length(); i++)
{
//JSONObject obj = (JSONObject) arr.get(i);
list.add(arr.get(i).toString());
}
load_data();
Follow this:
private List<String> list = new ArrayList<String>();
try{
JSONArray arr = json.getJSONArray("JSONArray Name");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
list.add(c.getString("Object Name"));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
load_data();

Categories

Resources