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;
}
};
}
Related
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.
I took sensor reading of bmp180 and passed to thingspeak and the graph was displayed.Now I want to get the json of thingspeak to my android phone.But the json in the thingspeak data is not getting in my phone.Any help would be appreciated.Here is my code:
public class MainActivity extends Activity {
private static final String PATIENTS_LIST_URL = "http://thingspeak.com/channels/201342/field/1.json";
ArrayList<HashMap<String, String>> patientList;
Button button;
TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button_get_string);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetJsonData();
}
});
}
private void GetJsonData() {
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
PATIENTS_LIST_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Toast.makeText(MainActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
textview.setText(response.toString());
try {
JSONArray data = response.getJSONArray("feeds");
JSONObject eachData = data.getJSONObject(0);
String address=eachData.getString("field2");
// Toast.makeText(getApplicationContext(),
// "field1::"+address, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
// Snack(error.getMessage());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String>map = new HashMap<String,String>();
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjReq);
}
}
field2 doesn't exist in the feeds part of the Json response.
Try changing
String address = eachData.getString("field2");
to
String address = eachData.getString("field1");
Truncated response from your URL for reference:
{
"channel":{
"id":201342,
"name":"Weather Monitoring Station",
"description":"The channel provides live weather information of the city such as temperature and atmospheric pressure.",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Temperature",
"field2":"Pressure",
"created_at":"2016-12-09T08:32:45Z",
"updated_at":"2017-02-10T15:46:27Z",
"last_entry_id":371
},
"feeds":[
{
"created_at":"2017-01-26T07:33:03Z",
"entry_id":272,
"field1":"29.57"
},
{
"created_at":"2017-01-26T07:33:25Z",
"entry_id":273,
"field1":"29.61"
}
....
]
}
After the login I get this response from the webserver..
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
Ok. Now My android code.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This code Toast the following message. "Bem vindo lu#lu.com"
What I want is:
How can I get the other infos and pass it to a String.
Email = "lu#lu.com"
Endereco = "Rua Pedro..."
Name = "Lu Zimermann"
Soo I can use it later on the app.
Thanks.
Now the response is the right way you can do this to save data..
first wirte a custion class for Preferennce
SharedPreferenceCustom
public class SharedPreferenceCustom {
private Context mContext;
private String defValue = "";
public SharedPreferenceCustom(Context context) {
this.mContext = context;
}
public void setSharedPref(String inputKey, Object inputValue) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getString(inputKey, defValue);
}
}
Now for saving the data, in the activity
try {
JSONObject response = new JSONObject(new String(response_from_server))
SharedPreferenceCustom sp = new SharedPreferenceCustom(Activity.this);
sp.setSharedPref("key_1", response.getString("nomeusuario")); // use key as per needed
sp.setSharedPref("key_2", response.getString("enderecousuario"));
sp.setSharedPref("key_3", response.getString("telefoneusuario"));
sp.setSharedPref("key_4", response.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
And for getting the data call sp.getSharedPref("key"); pass the key for getting the corresponding data
EDIT: you can also write individual function in SharedPreferenceCustion to store different data type, or you can use just this, But it might create some conflicts for certain data types,
Hope this helps :) :)
To get access to the other keys, you can use the get(key) on the jsonObject object. Here are the code changes you need to make:
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
//here I am just getting the other properties/keys
String nomeusuario = jsonObject.getString("nomeusuario");
String enderecousuario = jsonObject.getString("enderecousuario");
String telefoneusuario = jsonObject.getString("telefoneusuario");
//here you could do whatever you like - I am just making a Toast as an example:
Toast.makeText(getApplicationContext(), nomeusuario+ ", "+enderecousuario+ ", "+telefoneusuario ,Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I hope this helps you - give it a try and let me know.
By the way, I am assuming the JSON that you are getting is proper.
There are several ways you can do that.
First of all you need to store them into variable/s.
You can choose to keep it as JSON var, as HashMap or each variable separate as String.
The second action is to access it from any place. This depends on how long to you want the information alive.
If you want them live for just as long as the app is live then the I suggest to create a Global Java class with set/get of your variable.
You could also store it in SharedPreferences or sqlite database for permanent.
Try following
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if(jsonObject.names().get(0).equals("success")){
//Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
String values = "";
while(keys.hasNext()){
String keyName = keys.next();
values = jsonObject.getString(keyName) + "\n";
}
Toast.makeText(getApplicationContext(),values,Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I have a switch as shown below.
I enter the League's name,and a league is created via a web service.
The switch code is.
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
openLeague="OPEN";
}else{
openLeague = "CLOSED";
}
}
});
The button code...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session = new SessionManager(getApplicationContext());
leagueName = teamTextField.getText().toString();
if (!leagueName.isEmpty()) {
createLeague(leagueName, username, password, start, end, openLeague);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
The createLeague(...) contains the web service. I am posting six variables. The one I am interested is the open_league.
private void createLeague(final String leagueName, final String username, final String password,final String start,final String end,final String openLeague) {
String tag_json_obj = "json_obj_req";
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("league_name",leagueName);
postParams.put("username",username);
postParams.put("password",password);
postParams.put("league_start",start);
postParams.put("league_finish",end);
postParams.put("open_league",openLeague);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CREATE_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if (response.getString("status").equals("success")){
Intent i = new Intent(CreateLeague.this, League.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
// VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjRequest);
}
I put a breakpoint before this line
sonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CREATE_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>()
to check the json I am sending. So when the switch is open I get.
{
"league_start":"28-07-2015 09:37:43",
"username":"cerberus_30#gmail.com",
"league_finish":"11-08-2015 09:37:43",
"league_name":"Samsung League",
"password":"larissa",
"open_league":"OPEN"
}
You see the open_league json variable is open. However when the switch is closed,the open_league variable is null! Why is this? I have put in my switch listener the open_league to be "OPEN" when it is on when CLOSED when it is OFF. Thanks.
Your mistake is simple, just fix this,
open_league = "CLOSED";
You haven't initialized the variable but is trying to use it.
When the Switch is opened there is no problem, as the variable has been assigned to "OPEN"
But when you are trying to use it in the closed state, you are getting null values as the variable haven't been initialized
Always remember to initialize the variables to the default values in this kind of scenarios. In your case the default value is "CLOSED" to just initialize it to "CLOSED".
Let's say I have this Dashboard.java:
public class DashboardActivity extends ActionBarActivity {
private TextView login_response;
private static String TAG = DashboardActivity.class.getSimpleName();
final static String API_URL_ACCOUNT = "http://www.example.com/apiv2/account";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
login_response = (TextView) findViewById(R.id.login_response);
Intent intent = getIntent();
if(intent.hasExtra("TOKEN"))
{
String token = intent.getStringExtra("TOKEN");
getShopName(token);
}
else
{
}
And this is the getShopName method:
private void getShopName(String token) {
JsonObjectRequest req = new JsonObjectRequest(API_URL_ACCOUNT + "?token=" + token, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
JSONArray account = response.getJSONArray("account");
//Log.d(TAG, "Account: "+account.toString());
JSONObject shop = account.getJSONObject(0);
String name_shop = shop.getString("name_shop");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
VolleyController.getInstance().addToRequestQueue(req);
}
My goal is to have
if(intent.hasExtra("TOKEN"))
{
String token = intent.getStringExtra("TOKEN");
String shop_name = getShopName(token);
}
The "shop_name" in variable, to reuse in other part.
So, I know that void doesn't return nothing, but, I tried to edit like this answer, without success:
How can I return value from function onResponse of Volley?
Thank you
The issue is not returning a value from a JsonObjectRequest, but rather that you're trying to do an asynchronous operation in a synchronous way.
Here is a great explanation: Asynchronous vs synchronous execution, what does it really mean?
And to your specific question: I advise using an AsyncTask for your network operation.