Iterating a JSONObject doesn't fill the spinner - android

I have an issue that i unable to understand i.e when i make an http request i get following JSONObject as response. I have to loop-iterate every keys, take the data that i need, build them in an object and fill the spinner, but i think there is something wrong in the loop or i don't know, cause when i take every object, alone without a loop, all work fine,
when i loop to build object and add to array list dynamically it don't work:
{
"Conteggio": 2,
"0": {
"Distributore Information": {
"id_distributore": "1",
"NomeDistributore": "Colonnina 0",
"litriiniziocolonna": "444",
}
},
"1": {
"Distributore Information": {
"id_distributore": "2",
"NomeDistributore": "Colonnina 1",
"litriiniziocolonna": "555",
}
}
}
I know that it's wrong loop through a JSONObject but i cant change this JSON.
Here the android code code:
private void getInfoColonnina(){
String url = "https://icantshowtheurlbutitworkfine_module.json";
final SharedPreferences myPref = getSharedPreferences("loginPref", MODE_PRIVATE);
final SharedPreferences.Editor myPreff = myPref.edit();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<DistrBean> distrBeansList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
Object key = keys.next();
JSONObject value = jsonObject.getJSONObject((String) key);
JSONObject info = value.getJSONObject("Distributore Information");
String LitriColonnina1 = info.getString("litriiniziocolonna");
String NomeDistributore1 = info.getString("NomeDistributore");
String id_distributore1 = info.getString("id_distributore");
DistrBean distrBean = new DistrBean();
distrBean.setLitriColonnina(LitriColonnina1);
distrBean.setNomeDistributore(NomeDistributore1);
distrBean.setIdDistributore(id_distributore1);
distrBeansList.add(distrBean);
}
ArrayAdapter<DistrBean> adapter = new ArrayAdapter<DistrBean>(InizioTurnoActivity.this, android.R.layout.simple_spinner_item, distrBeansList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DistrBean distrBean = (DistrBean) adapterView.getSelectedItem();
getSelectedDistr(distrBean);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(InizioTurnoActivity.this, "CHIAMATA INFOCOLONNINA FALLITA", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
}
public void getSelectedDistr(DistrBean v){
DistrBean distrBean = (DistrBean) spinner.getSelectedItem();
setDistrData(distrBean);
}
private void setDistrData(DistrBean distrBean){
String name = distrBean.getNomeDistributore();
String litri = distrBean.getLitriColonnina();
String id = distrBean.getIdDistributore();
tvProgressivo.setText(litri);
tvColonnina.setText(name);
Toast.makeText(this, "Hai selezionato " + name + "che ha litri: " + litri, Toast.LENGTH_LONG).show();
}
}
Can you guys help me? thank you in advance!

your json is not valid
{
"Conteggio": 2,
"0": {
"Distributore Information": {
"id_distributore": "1",
"NomeDistributore": "Colonnina 0",
"litriiniziocolonna": "444", //this line
}
},
"1": {
"Distributore Information": {
"id_distributore": "2",
"NomeDistributore": "Colonnina 1",
"litriiniziocolonna": "555", //this line
}
}
}

You should test your rest api on postman before integrating it in android app and use Gson library, response model to handle all json response. Gson library automatically parse data according to your model so you dont need to get data by specifying individual key.

I think that your parsing algorithm has issue.
Iterator keys = jsonObject.keys();
-> Conteggio, 0, 1
So you should skip one.

Related

Troubles with JSON parsing

I'm working on a simple news app.
I need to fetch data from a remote server in JSON format then put it in view. I use TabLayout and recyclerView to display data categories and Volley for the query no API here.
The TabLayout is set automatically depending on data from JSON where I extract tabs title and the content of every tab is being displayed on recyclerView (Article title, image, content, links...) and rendered inside a fragment
I spent several hours trying to debug it without success., but whatever I do, no data is being displayed. Not sure what I'm doing wrong.
I know this is not the right place to ask for such things, but I'm a bit of a desperate and would need some experienced developer than me look at my problem.
How it works:
Activity launches BaseArticleFragment which calls a method that loads contents categories and bind the data to the views:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.fm = getSupportFragmentManager();
this.baseArticleFragment = new BaseArticleFragment();
FragmentTransaction ft = this.fm.beginTransaction();
ft.add(R.id.fragment_container, this.baseArticleFragment, TAB_LAYOUT_FRAGMENT_TAG);
ft.commit();
}
When launched, baseArticleFragment calls loadCategories() method inside its onActivityCreated() method:
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
loadCategories();
}
here is the loadCategories() method:
private void loadCategories(){
String url = "http://somesite.com/categories"; //link to grab the json data
ApplicationController.getInstance().addToRequestQueue(
new JsonObjectRequest(0, url, null, new Listener<JSONObject>() { //0 is the Volley code for GET method
#Override
public void onResponse(JSONObject jsonObject) {
BaseArticleFragment.categories = JSONParser.parseCategories(jsonObject);
BaseArticleFragment.this.mViewPager.setAdapter(
new RecyclerViewFragmentPagerAdapter(BaseArticleFragment.this.getChildFragmentManager(),
BaseArticleFragment.categories));
BaseArticleFragment.this.mTabLayout.setupWithViewPager(BaseArticleFragment.this.mViewPager);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError vError){
Log.d("BaseArticleFragment", "---Volley Error---");
Snackbar.make(BaseArticleFragment.this.mTabLayout, R.string.error_load_categories, Snackbar.LENGTH_SHORT)
.setAction(R.string.action_retry, new View.OnClickListener() {
#Override
public void onClick(View v) {
BaseArticleFragment.this.loadCategories();
}
}).show();
}
}));
}
I guess the problem may be with the query but not sure cause I think my logic here is good
EDIT :
Here is the JSON data I need to fetch:
[
{
"name": "Topic 1",
"tid": "2",
},
{
"name": "Topic 2",
"tid": "3",
},
{
"name": "Topic 3",
"tid": "4",
},
{
"name": "Topic 4",
"tid": "5",
},
{
"name": "Topic 5",
"tid": "6",
},
{
"name": "Topic 6",
"tid": "1415",
},
{
"name": "Topic 7",
"tid": "1414",
},
{
"name": "Topic 8",
"tid": "1298",
},
{
"name": "Topic 9",
"tid": "1301",
},
{
"name": "Topic 10",
"tid": "1299",
},
{
"name": "Topic 11",
"tid": "1302",
},
{
"name": "Topic 12",
"tid": "1300",
},
{
"name": "Topic 13",
"tid": "1297",
}
]
Edit 2:
I forget to paste the code for parseCategories() in my JSONPArser class
public static ArrayList<Category> parseCategories(JSONObject jsonObject) {
ArrayList<Category> categoryArrayList = new ArrayList<>();
try {
JSONArray categories = jsonObject.getJSONArray("categories");
Category all = new Category();
all.setTid("0");
all.setName(ApplicationController.getInstance().getString(R.string.tab_all));
categoryArrayList.add(all);
for (int i = 0; i < categories.length(); i++) {
JSONObject catObject = categories.getJSONObject(i);
Category category = new Category();
category.setTid(catObject.getString("tid"));
category.setName(catObject.getString("name"));
categoryArrayList.add(category);
}
return categoryArrayList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
Try this #esQmo_,
StringRequest stringRequest = new StringRequest(url , new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
ArrayList<Hashmap<String,String>> arraylist = new
ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hashMap = new HashMap<>();
String name =
jsonArray.getJSONObject(i).getString("name");
String tid =
jsonArray.getJSONObject(i).getString("tid");
hashMap.put("name", name);
hashMap.put("tid ", tid );
arraylist.add(hashMap);
Log.e("response",name + "\n" + tid);
}
attachAdapter(arraylist);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
//setting adapter data to the RecyclerView
private void attachAdapter(ArrayList<HashMap<String, String>>
arrayList) {
ExampleAdapter adapter = new ExampleAdapter(arrayList,this);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
This is the adapter class
public class ExampleAdpater extends RecyclerView.Adapter<ExampleAdpater.ExampleViewHolder>{
public ArrayList<HashMap<String,String>> arraylist;
public Context context;
public ExampleAdpater(ArrayList<HashMap<String, String>> arraylist, Context context) {
this.arraylist= arraylist;
this.context = context;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.textLayout,viewGroup,false);
return new ExampleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder viewHolder, int i) {
HashMap<String,String> hashMap = arraylist.get(i);
viewHolder.name.setText(hashMap.get("name"));
viewHolder.tid.setText(hashMap.get("tid"));
}
#Override
public int getItemCount() {
return arraylist.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder{
TextView name,tid;
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
tid = itemView.findViewById(R.id.tid);
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), ""+name.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
textLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tid"
/>
</LinearLayout>
You forgot to add this thing at the end of the "load" method:
Volley.newRequestQueue(this).add(jsonRequest);
Try to add it...
Instead of using new RequestQueue, please use RequestQueue jsonQueue = new RequestQueue
Like this:
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://someurl.com/api";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray ja = new JSONArray(response);
for(int i = 0; i < ja.length(); i++)
{
JSONObject jo = ja.get(i);
String name = jo.getString("name");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
requestQueue.add(jsonObjectRequest);
Just check if you have set LayoutManager for recyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(MyActivity.this));
Can we have your code and JSON data too? Since we can't read what's on your mind or on your computer... Plase make some edits to your post, add code and json data so we may help you.
Since you are getting a timeout error you can change the timeout value so that it will be willing to wait longer.
Try something like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
where MY_SOCKET_TIMEOUT_MS is amount of time (in milliseconds) you want to wait before a timeout. Start with 5000 (5 seconds) and play around with it.
Do this before
requestQueue.add(jsonObjectRequest);

Requesting JSON with Volley

I'm trying to do an application that display some article stored in a SQLite database.
I use a php function on my server to get a JSON file containing my database. In my Android app I want to get that JSON and put it in a JSONObject, I did the following :
private void initDataset() {
mDataset = new ArrayList<>();
Log.d("InitDataset", String.valueOf(mDataset.size()));
getArticles();
Log.d("InitDataset", String.valueOf(mDataset.size()));
}
public void getResponse(int method, String url, JSONObject jsonValue, final VolleyCallback callback) {
StringRequest strreq = new StringRequest(method, url, new Response.Listener < String > () {
#Override
public void onResponse(String Response) {
callback.onSuccessResponse(Response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
e.printStackTrace();
Toast.makeText(getContext(), e + "error", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strreq);
}
public void getArticles() {
getResponse(Request.Method.GET, AppConfig.URL_ARTICLE, null,
new VolleyCallback() {
#Override
public void onSuccessResponse(String result) {
for (int i = 1; i < 3; i++) {
try {
Article article = new Article();
JSONObject response = new JSONObject(result);
// Now store the articles in SQLite
JSONObject articleObj = response.getJSONObject("article" + i);
article.setArticle_id(i);
article.setPicture_url(articleObj.getString("picture_url"));
article.setName(articleObj.getString("name"));
article.setDescription(articleObj.getString("description"));
article.setQuantity(Float.parseFloat(articleObj.getString("quantity")));
article.setPrice(Float.parseFloat(articleObj.getString("price")));
mDataset.add(article);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
public interface VolleyCallback {
void onSuccessResponse(String result);
}
But in the Log, the size of mDataset is always 0. Or if I Log for example the name of the article in onResponse() I can see every name is in the database. (thus the connection and php function are alright I think)
Any idea ?
Here is the php file :
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// JSON response array
$response = array("error" => FALSE);
$article = $db->getAllArticles();
if ($article != false) {
// use is found
$response["error"] = FALSE;
while($row = $article->fetch_assoc()) {
$response["article".$row["article_id"]]["article_id"] = $row["article_id"];
$response["article".$row["article_id"]]["picture_url"] = $row["picture_url"];
$response["article".$row["article_id"]]["name"] = $row["name"];
$response["article".$row["article_id"]]["description"] = $row["description"];
$response["article".$row["article_id"]]["quantity"] = $row["quantity"];
$response["article".$row["article_id"]]["price"] = $row["price"];
}
echo json_encode($response);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Error";
echo json_encode($response);
}
?>
And the JSON I get when executing the php :
{
"error": false,
"article1": {
"article_id": "1",
"picture_url": "https://static.webshopapp.com/shops/019852/files/024106649/600x600x2/brasserie-dachouffe-la-chouffe-33cl.jpg",
"name": "Chouffe",
"description": "Ceci est une description de la chouffe.",
"quantity": "33",
"price": "2.54"
},
"article2": {
"article_id": "2",
"picture_url": "https://www.latelierdesbieres.fr/1266-large_default/biere-belge-noel-n-ice-chouffe-33-cl.jpg",
"name": "Chouffe de Noel",
"description": "Ceci est une description de la chouffe de Noel.",
"quantity": "33",
"price": "3.23"
}
}
You're misunderstanding some asynchronous execution ordering.
You need to rewrite your method to wait for the returned results, not immediately log the list size twice without letting the network call finish
getArticles(new VolleyCallback() {
#Override
public void onSuccessResponse(String result) {
// parse result
// print list size <-- shouldn't be empty
}
});
// your list will be empty here still
Where the method is defined as
public void getArticles(VolleyCallback vcb) {
getResponse(Request.Method.GET, AppConfig.URL_ARTICLE, null, vcb);
}
However, that seems really pointless to wrap two methods when you could just call getResponse directly with the correct parameters

how to set text according to country item in android?

I am getting country name from spinner , now i want to set country code according to spinner item in edittext ...but i dont to know how to set according to spinner item ...
this is code (here i am getting country name from spinner):
pmmobile = (EditText) findViewById(R.id.mob);
private void getCountryData(){
StringRequest stringRequest = new StringRequest(DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
Log.d("Test",response);
JSONArray result = new JSONArray(response);
//Calling method getCountry to get the Country from the JSON Array
getCountry(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}});
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getCountry(JSONArray jsonArrayCountry){
//Traversing through all the items in the json array
List<Country> countries = new ArrayList<>();
try {
String country_name, country_code;
JSONObject countries_object;
for (int i = 0; i < jsonArrayCountry.length(); i++) {
countries_object = jsonArrayCountry.getJSONObject(i);
country_code = countries_object.getString("id");
country_name = countries_object.getString("Name");
countries.add(new Country(country_code, country_name));
}
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
pmcountry.setPrompt("Select Country");
pmcountry.setAdapter(countryAdapter);
pmcountry.setAdapter(new NothingSelectedSpinnerAdapter(countryAdapter,
R.layout.contact_spinner_row_nothing_selected,this));
pmcountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
} catch (JSONException e) {
Log.e("PMSearchActivity", e.getLocalizedMessage(), e);
}
}
i want to set country code in pmmobile..kindly help, new to android.
this is my json:
[
{
"id": "1",
"Name": "Afghanistan",
"CountryCode": "AF",
"CountryIso": "AFG"
},
{
"id": "2",
"Name": "Albania",
"CountryCode": "AL",
"CountryIso": "ALB"
},
I suppose that if you want to display a String you are going to use a TextView, not an EditText.
Anyway:
pmmobile.setText(<... string or string res ID ...>);
Simple as that.
To keep it asynchronous I suppose that you should put this inside one of your listeners, for example onItemSelected().
Update.
Being not aware of what you are trying to do, I suggest you anyway to browse the constants inside the Locale utility class. You can get all the language ISO codes and what you need from handy constants and utilities from there, without getting crazy with json and similar stuff.
Locale.COUNTRY.getLanguage();
or
Locale.getISOLanguages();
Although I don't know if this is what you need.

How to get the id of the selected item of the Autocompletetextview in android?

My question is when i select the state from the autocompletetextview it always return 1 as an id. but i want to get the id accordingly to the state as per shown my json. Example (StateName = Assam then StateId = 4).but i am always getting id as 1. i am using model class to set the id and get from it.but there is no change i am getting the id as a 1. If anyone know how can i resolve this problem.then please tell me. thanks in advance.
This is my jsonResponce :-
{
"ReplyCode": 1,
"Message": "Franchisee and Plans List",
"data2": [
{
"StateId": 1,
"StateName": "Andaman and Nicobar Island",
"CountryId": 1
},
{
"StateId": 2,
"StateName": "Andhra Pradesh",
"CountryId": 1
},
{
"StateId": 3,
"StateName": "Arunachal Pradesh",
"CountryId": 1
},
{
"StateId": 4,
"StateName": "Assam",
"CountryId": 1
},
This is the method by which i am getting the data from the json :-
public void volleyStatedata() {
if (mGeneralUtilities.isConnected()) {
mProgressDialog.show();
StringRequest stateRequest = new StringRequest(Request.Method.POST, GlobalData.REGISTER_DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mProgressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data2");
for (int i = 0; i < jsonArray.length(); i++) {
PojoState pojoState = new PojoState();
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String stateId = jsonObject1.getString("StateId");
String stateName = jsonObject1.getString("StateName");
mStateList.add(stateName);
mStateIdList.add(stateId);
pojoState.setmStateList(mStateList);
pojoState.setmStateId(stateId);
mpojoStateList.add(pojoState);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("error", "" + volleyError.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue stateQueue = Volley.newRequestQueue(getContext());
stateQueue.add(stateRequest);
} else {
mGeneralUtilities.showAlertDialog("Hey User !", "Please connect to the internet", "Ok");
}
}
And this is my adapter where i am applying onItemclick listner on the autocompltetextview :-
ArrayAdapter<String> mStateAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mStateList);
mActState.setAdapter(mStateAdapter);
mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mpojoStateList.get(i).getmStateId();
}
});
Your code uses i that returns in the onItemClick callback, which refers to the item you clicked from the visible items in the auto-complete list, not your original list. When you click on the first item in the auto-complete list, i=0, which means it always returns the "Andaman and Nicobar Island" item whose StateId=1.
Off the top of my head, you can get the item String from the mStateAdapter and compare it to your mpojoStateList and find the corresponding item. (Check the sample code)
final ArrayAdapter<String> mStateAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, mStateList);
mActState.setAdapter(mStateAdapter);
mActState.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String itemName = mStateAdapter.getItem(i);
for (PojoState pojo : mpojoStateList) {
if (pojo.mStateName.equals(itemName)) {
String id = pojo.getmStateId(); // This is the correct ID
break; // No need to keep looping once you found it.
}
}
}
});
It also is better if, inside your PojoState object, you override your toString() method and make it return the mStateName, and pass the mpojoStateList to the adapter without having to make 3 ArrayLists. That way, mStateAdapter.getItem(i) will return a PojoState object instead of a String, and you can use its ID without referring to the returned position (i).

Parse JSON with both sides values

I'm using volley to get response from API but the response consist of STATE_ID:STATE_NAME pair (i.e. value:value pair) and I need both side's values in different Strings. I need these values to put in a spinner so that when user selects a State I can get its corresponding ID also.
// JSON response
{
"1": "West bengal",
"3": "Himachal Pradesh",
"4": "Maharashtra",
"11": "Queensland"
}
My Code
public class MainActivity extends AppCompatActivity {
private static final String STATE = "MY_API";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View v){
loginRequest();
}
private void loginRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, STATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country_id","2");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
You already have the iterate() method as we discussed in comments.
Done some work to give you value :
try {
JSONObject jsonObject = new JSONObject(response);
for (String key : iterate(jsonObject.keys()))
{
Toast.makeText(this, "Key : "+key+" Value: "+jsonObject.optString(key), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please refer the iterate method from this answer. I have posted this as a new answer because OP was unable to make it for the values..!!
I used iterator to find a key. May this will help:
private void parseRespone(String response){
try {
JSONObject MainjsonObject = new JSONObject(response)
Iterator<String> iter= MainjsonObject.keys();
//To get keys of an object
while (iter.hasNext())
{
String key = (String)iter.next();
//Object value = jsonobj.get(key); //To use by object
String valueStr = jsonobj.get.getString(key);
Log.i("Jsonparsing", "key= "+key + "\n Value=" +valueStr );
Toast.makeText(getActivity(),"key= "+ key + "\n value= " + valueStr ,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
I could find an unknown key by this.
Please check in a Log in your android studio...
here I have put Toast also..
And call this function here...
...........
#Override
public void onResponse(String response) {
parseRespone(response); //Function to parse json
}
Thanks..
It will be much better if you consider changing your response to something like this:
[
{"ID":"1","name": "West bengal"},
{"ID":"3","name": "Himachal Pradesh"},
{"ID":"4","name": "Maharashtra"},
{"ID":"11","name": "Queensland"}
]
You can use jsonObject.names() (or keys() for an Iterator) to retrieve all keys.
After that you can iterate through the array using the keys and store your strings.
https://developer.android.com/reference/org/json/JSONObject.html#names()
https://developer.android.com/reference/org/json/JSONObject.html#keys()
I tried this solution and it worked out.`Here, "key" will toast the key_value[1,3,4,11] and value will print the names[West bengal,Himachal Pradesh,Maharashtra,Queensland].
JSONObject list_object = inner_json_object.getJSONObject("");
for (String key : iterate(list_object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(Activity.this, ""+key, Toast.LENGTH_SHORT).show();
String value = bank_list_object.optString(key);
}`
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}

Categories

Resources