Sorry if this post is not correctly filled but ill try to do my best. I am attempting to create an android app with android studio where i need a TinderLike swipe holder.
For this purpose i am using this library: CardStackView
Everything is working fine if i use the default code to populate the pictures.
private List<TouristSpot> createTouristSpots() {
List<TouristSpot> spots = new ArrayList<>();
spots.add(new TouristSpot("Yasaka Shrine", "Kyoto", "https://source.unsplash.com/Xq1ntWruZQI/600x800"));
spots.add(new TouristSpot("Fushimi Inari Shrine", "Kyoto", "https://source.unsplash.com/NYyCqdBOKwc/600x800"));
spots.add(new TouristSpot("Bamboo Forest", "Kyoto", "https://source.unsplash.com/buF62ewDLcQ/600x800"));
spots.add(new TouristSpot("Brooklyn Bridge", "New York", "https://source.unsplash.com/THozNzxEP3g/600x800"));
spots.add(new TouristSpot("Empire State Building", "New York", "https://source.unsplash.com/USrZRcRS2Lw/600x800"));
spots.add(new TouristSpot("The statue of Liberty", "New York", "https://source.unsplash.com/PeFk7fzxTdk/600x800"));
spots.add(new TouristSpot("Louvre Museum", "Paris", "https://source.unsplash.com/LrMWHKqilUw/600x800"));
spots.add(new TouristSpot("Eiffel Tower", "Paris", "https://source.unsplash.com/HN-5Z6AmxrM/600x800"));
spots.add(new TouristSpot("Big Ben", "London", "https://source.unsplash.com/CdVAUADdqEc/600x800"));
spots.add(new TouristSpot("Great Wall of China", "China", "https://source.unsplash.com/AWh9C-QjhE4/600x800"));
return spots;
}
But when i try to change the default population code with a code that retrieve information from a database, nothing is displayed anymore.
private List<TouristSpot> createTouristSpots() {
final List<TouristSpot> spots = new ArrayList<>();
String url = AppData.api + "radar_2.php";
alerttext.setVisibility(View.VISIBLE);
SharedPreferences token = getApplicationContext().getSharedPreferences(AppData.sp_user_info, 0);
String user_id = token.getString(AppData.sp_user_id, "0");
UserData userData=new AppData().getUserData();
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("number", String.valueOf(n));
params.put("gender", userData.getLooking_gender());
params.put("looking_age_start",userData.getLooking_age_start());
params.put("looking_age_end", userData.getLooking_age_end());
params.put("latitude", userData.getLatitude());
params.put("longitude", userData.getLongitude());
params.put("distance", "100");
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
if (n == 1)
{
SharedPreferences.Editor editor = pref.edit();
editor.putString("MATCHDATALIST", response.toString());
editor.commit();
}
try
{
String str = response.getString("Error");
if (str.equals("None"))
{
JSONArray jsonArray = response.getJSONArray("Responsedata");
//Toast.makeText(getActivity(), jsonArray.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; jsonArray.length() > i; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
spots.add(new TouristSpot(jsonObject.getString("user_id"),jsonObject.getString("username"),jsonObject.getString("hometown"),jsonObject.getString("age"),jsonObject.getString("gender"),jsonObject.getString("profile_image"),jsonObject.getString("interests"),jsonObject.getString("distance")));
}
alerttext.setVisibility(View.GONE);
} else {
//Toast.makeText(getActivity(), response.getString("Error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError response)
{
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsObjRequest);
//Toast.makeText(getActivity(), spots.toString(), Toast.LENGTH_LONG).show();
return spots;
}
In my OnCreateView, i am calling the function reload();
private void reload() {
cardStackView.setVisibility(View.GONE);
adapter = createTouristSpotCardAdapter();
cardStackView.setAdapter(adapter);
cardStackView.setVisibility(View.VISIBLE);
}
private TouristSpotCardAdapter createTouristSpotCardAdapter() {
final TouristSpotCardAdapter adapter = new TouristSpotCardAdapter(getApplicationContext());
adapter.addAll(createTouristSpots());
return adapter;
}
I did checked the JSONArray to string and all information retrieved from the database is inside it.
PS: the TouristSpot is adapted to contain all the variables from the database.
If some one could bring me on the correct path to make it working with values retrieved from my database, i would be very gratfull
Sincerely,
Jeremy
Related
I want to execute taking data from JSON as shown below. But when
Toast.makeText(this, MangIDtrailer.size () + "..... check size of Array IDtrailer .....", Toast.LENGTH_LONG).show();
it returns 0.
I don't know what the cause is.
public class Main2Activity extends AppCompatActivity {
ListView Listmovie;
ArrayList<String> MangIDtrailer;
public static ArrayList<InfoMovie> inforMovieArrayList;
AdapterMovie adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
String url1 ="http://the....ying";
inforMovieArrayList = new ArrayList<>();
MangIDtrailer = new ArrayList<>();
MangIDtrailer = GetIDMovie(url1);
inforMovieArrayList = DataMovie(MangIDtrailer);
Listmovie = (ListView) findViewById(R.id.ListMovie);
adapter = new AdapterMovie(this, R.layout.movielist, inforMovieArrayList);
Listmovie.setAdapter(adapter);
Listmovie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Main2Activity.this,Review_Movie.class);
intent.putExtra("IDmovie",i);
//Toast.makeText(MainActivity.this, ""+i, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
public ArrayList<String> GetIDMovie (String Url) {
final ArrayList<String> ArrayID = new ArrayList<>();
final RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String IDTrailer;
JSONArray jsonArrayFreeMovies = response.getJSONArray("FreeMovies");
for (int i=0; i < jsonArrayFreeMovies.length(); i++) {
JSONObject jsonObjectFreeMovies = jsonArrayFreeMovies.getJSONObject(i);
IDTrailer = jsonObjectFreeMovies.getString("trailer_id");
ArrayID.add(IDTrailer);
Toast.makeText(Main2Activity.this, i+"************", Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, MangIDtrailer.get(2)+"check Data ", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
queue.cancelAll(jsonObjectRequest);
return ArrayID;
}
public ArrayList <InfoMovie> DataMovie (ArrayList<String> MangIDtrailer) {
final ArrayList<InfoMovie> inforMovieArray = new ArrayList<>();
final String linkDetail = "http://tk/api/trailers/movDetail?trailer_id=";
final RequestQueue queue2 = Volley.newRequestQueue(this);
//////////////Check that MangIDtrailer.size () has no data////////////////////////////////////
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
for (int i=0; i<MangIDtrailer.size(); i++) {
JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.GET, linkDetail + MangIDtrailer.get(i) + "&test_fullVer=1", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String linkposter, linkbackdrop, namemovie, overviewmovie, Release_date, Urltrailer;
Float Vote_average;
String linkHot = "https://image.tmdb.org/t/p/w500/";
JSONObject jsonObjectInfo = null, jsonObjectMore = null;
JSONObject jsonopFreeMovies1 = response.getJSONObject("FreeMovies");
if (jsonopFreeMovies1.has("FreeMovies")) {
//Toast.makeText(MainActivity.this, "Cos ", Toast.LENGTH_SHORT).show();
JSONObject jsonObjectFreeMovies2 = jsonopFreeMovies1.getJSONObject("FreeMovies");
jsonObjectInfo = jsonObjectFreeMovies2.getJSONObject("Info");
jsonObjectMore = jsonObjectFreeMovies2.getJSONObject("More");
} else {
//Toast.makeText(MainActivity.this, "Khoong cos", Toast.LENGTH_SHORT).show();
jsonObjectInfo = jsonopFreeMovies1.getJSONObject("Info");
jsonObjectMore = jsonopFreeMovies1.getJSONObject("More");
}
namemovie = jsonObjectInfo.getString("title");
Urltrailer = jsonObjectInfo.getString("trailer_urls");
linkposter = linkHot + jsonObjectInfo.getString("thumbnail");
overviewmovie = jsonObjectMore.getString("overview");
linkbackdrop = linkHot + jsonObjectMore.getString("backdrop_path");
Release_date = jsonObjectMore.getString("release_date");
Vote_average = Float.valueOf(jsonObjectMore.getLong("vote_average"));
inforMovieArray.add(new InfoMovie(namemovie, overviewmovie, linkposter, linkbackdrop, Vote_average, Release_date));
Toast.makeText(Main2Activity.this,namemovie + "-" + overviewmovie + "-" + Vote_average, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(Main2Activity.this, "Lỗi", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "Lỗi Try catch", Toast.LENGTH_SHORT).show();
}
});
queue2.add(jsonObjectRequest2);
}
return inforMovieArray;
}
}
As you suggested
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
This is where you are getting size zero, which is absolutely true, because you have only initialized your array MangIDtrailer and it is an empty array. Your function GetIDMovie(url1); has a loop which populates your MangIDtrailer array which is below where you have called the toast. So your array is empty and thus its size returns zero.
One handy tip for you, you should name your functions in camelCase with first letter of your word in lowercase. GetIDMovie(url1) seems more like a class constructor. :)
EDIT:
The above solves your initial problem.
To fully solve your problem, you have to understand that Network Operations are asynchronous, meaning they will execute after sometime or they may return no value at all depending on various conditions, like network bandwidth, your server state, the parameters passed to your HTTP requests, etc.
You have two network calls in your above code; in functions: GetIDMovie() and DataMovie(). The second function requires an array of IDs which is only available if your first request is complete and returns an array of ids. So what you would want to do is, only after you get the array of ids ie. in onResponse of GetIDMovie() after the for loop, you should make a call to DataMovie().
This however is really ugly solution. I hope you will research further for better solution.
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'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
I am making an application which has a profile section for user data. Where a person can update the data such as college, university, branch. I have saved this data in shared preference when the person logged in the application and from that shared preference data, all the information of a user has been provided. How to instantly change the preferences data and set to the whole app. Well I am new in developing field os need help in getting things done.
Here is my code for updating user data activity
public void edit_user_data(){
final String str_new_name = _edit_prof_name_.getText().toString().trim();
linearLayout.setVisibility(View.VISIBLE);
ObjectAnimator flip = ObjectAnimator.ofFloat(imgSpoon, "rotationY", 0f, 180f);
flip.setDuration(800);
flip.setRepeatCount(Animation.INFINITE);
flip.start();
StringRequest strReq = new StringRequest(Request.Method.POST,
URLconstant.USER_UPDATE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
linearLayout.setVisibility(View.INVISIBLE);
try {
JSONObject data = new JSONObject(response);
JSONObject updatedata = data.optJSONObject("data");
int intError = updatedata.getInt("status");
boolean error = (intError > 0) ? true : false;
if(intError == 1){
String msg = updatedata.optString("msg");
Toast.makeText(ActivityUserEditProfile.this, msg, Toast.LENGTH_SHORT).show();
JSONArray data_array = new JSONArray("data");
for (int i = 0;i<=data_array.length();i++){
JSONObject data_obj = data_array.getJSONObject(i);
/* UserProfileData userdata = new UserProfileData();
userdata.setFullname(data_obj.getString("fullname"));
userdata.setUniverId(data_obj.getString("univer_id"));
userdata.setMuniversity(data_obj.getString("university"));
userdata.setCollegeid(data_obj.getString("collegeid"));
userdata.setMcollege(data_obj.getString("college"));
userdata.setBranchid(data_obj.getString("branchid"));
userdata.setMbranch(data_obj.getString("branch"));
userdata.setSemid(data_obj.getString("semid"));
userdata.setMsemester(data_obj.getString("semester"));
userdata.setUserImage(data_obj.getString("user_image"));
userdata.setUserId(data_obj.getString("user_id"));
userdata.setPassword(data_obj.getString("password"));
updated_info(data_obj);
SharedPreferences preferences = getApplicationContext().getSharedPreferences(SHARED_PRE_LOGIN_REGISTRATION, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
*//* preferences.edit().remove(FULL_NAME);
preferences.edit().remove(UNIVER_ID);
preferences.edit().remove(BRANCH_ID);
preferences.edit().remove(COLLEGE_ID);
preferences.edit().remove(SEM_ID);*//*
editor.clear();
editor.commit();
PreferenceHelper preferenceHelper = new PreferenceHelper();
preferenceHelper.getInstance(context).setBranchid(userdata.getBranchid());
preferenceHelper.getInstance(context).setCollegeid(userdata.getCollegeid());
preferenceHelper.getInstance(context).setEnrollno(userdata.getEnrollno());
preferenceHelper.getInstance(context).setFullname(userdata.getFullname());
preferenceHelper.getInstance(context).setMobile(userdata.getMobile());
preferenceHelper.getInstance(context).setSemid(userdata.getSemid());
preferenceHelper.getInstance(context).setUniverId(userdata.getUniverId());
preferenceHelper.getInstance(context).setUserId(userdata.getUserId());
preferenceHelper.getInstance(context).setUserImage(userdata.getUserImage());
preferenceHelper.getInstance(context).setMuniversity(userdata.getMuniversity());
preferenceHelper.getInstance(context).setMcollege(userdata.getMcollege());
preferenceHelper.getInstance(context).setMbranch(userdata.getMbranch());
preferenceHelper.getInstance(context).setMsemester(userdata.getMsemester());
preferenceHelper.getInstance(context).setPassword(userdata.getPassword());*/
}
}else{
String msg = updatedata.optString("msg");
Toast.makeText(ActivityUserEditProfile.this, msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
// pDialog.hide();
linearLayout.setVisibility(View.INVISIBLE);
}
}){
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("fullname",str_new_name);
params.put("univer_id",u_id);
params.put("collegeid",c_id);
params.put("branchid",b_id);
params.put("semid",s_id);
params.put("mobile",PreferenceHelper.getInstance(getApplicationContext()).getMobile());
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(strReq);
}
For this You can do this
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// your stuff here
}
};
For Details can you follow this android developer Documentation
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;
}
};
}