How to load replace json values in spinner? - android
I am new in android,I have one application,in my application i am getting user's profile data,here in my profile data i am getting user's state and city which user had previously set,like right now user set following state and city,and i am able to display that state and city in my spinner
{
"user_city": "Kolkata",
"user_state": "West Bengal",
}
Now issue is if user want to change state like from WestBengal to Karnataka,then i need to display all state and make user to change,so for that i have other separate webservice for load all state and i want to display that all state in same that spinner,but right now issue is i need to click two times then only it is showing all states
this is the response
[{"user_status":"1","state_id":"1","state":"Karnataka"},{"user_status":"1","state_id":"2","state":"Tamilnadu"},{"user_status":"1","state_id":"3","state":"Maharastra"},{"user_status":"1","state_id":"4","state":"Andhra Pradesh"},{"user_status":"1","state_id":"5","state":"West Bengal"},{"user_status":"1","state_id":"6","state":"Delhi"},{"user_status":"1","state_id":"8","state":"Andaman & Nicobar Islands"},{"user_status":"1","state_id":"9","state":"Arunachal Pradesh"},{"user_status":"1","state_id":"10","state":"Bihar"},{"user_status":"1","state_id":"11","state":"Chattisgarh"},{"user_status":"1","state_id":"12","state":"Dadra & Nagar Haveli"},{"user_status":"1","state_id":"13","state":"Daman & Diu"},{"user_status":"1","state_id":"14","state":"Goa"},{"user_status":"1","state_id":"15","state":"Gujarat"},{"user_status":"1","state_id":"16","state":"Haryana"},{"user_status":"1","state_id":"17","state":"Himachal Pradesh"},{"user_status":"1","state_id":"18","state":"Jharkhand"},{"user_status":"1","state_id":"19","state":"Kerala"},{"user_status":"1","state_id":"20","state":"Lakshadweep"},{"user_status":"1","state_id":"21","state":"Madhya pradesh"},{"user_status":"1","state_id":"22","state":"Pondichery"},{"user_status":"1","state_id":"23","state":"Punjab"},{"user_status":"1","state_id":"24","state":"Rajasthan"},{"user_status":"1","state_id":"25","state":"Sikkim"},{"user_status":"1","state_id":"26","state":"Telangana"},{"user_status":"1","state_id":"27","state":"Tripura"},{"user_status":"1","state_id":"28","state":"Uttaranchal"},{"user_status":"1","state_id":"29","state":"Uttar Pradesh"},{"user_status":"1","state_id":"31","state":"Nagaland"},{"user_status":"1","state_id":"32","state":"Mizoram"},{"user_status":"1","state_id":"33","state":"Meghalaya"},{"user_status":"1","state_id":"34","state":"Manipur"},{"user_status":"1","state_id":"35","state":"Assam"},{"user_status":"1","state_id":"36","state":"Chandigarh"},{"user_status":"1","state_id":"37","state":"Orissa"},{"user_status":"1","state_id":"38","state":"Others"}]
Loading profile
class LoadAllProdetails extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
private JSONObject jsonObjsss;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(GET_PRO_DETAILS, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObjsss = new JSONObject(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
profilessstates=new ArrayList<HashMap<String,String>>();
profilecitis=new ArrayList<HashMap<String,String>>();
if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("0"))
{
final String msgs=jsonObjsss.getString("message");
System.out.println("Messagessss"+msgs);
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(getActivity(), msgs, Toast.LENGTH_LONG).show();
}
});
}
else if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("1")) {
HashMap<String, String> mapzz = new HashMap<String, String>();
usersstatus = jsonObjsss.getString(GET_PRO_USERSTATUS);
usersfname = jsonObjsss.getString(GET_PRO_FIRSTNAME);
usersmails = jsonObjsss.getString(GET_PRO_EMAILS);
usersmob = jsonObjsss.getString(GET_PRO_MOBILE);
usersdobs = jsonObjsss.getString(GET_PRO_DATES);
usersaddresss = jsonObjsss.getString(GET_PRO_ADDRESS);
userszipss = jsonObjsss.getString(GET_PRO_ZIP);
userstates=jsonObjsss.getString(GET_PRO_STATE);
usercitys=jsonObjsss.getString(GET_PRO_CITY);
mapzz.put(GET_PRO_STATE, jsonObjsss.getString(GET_PRO_STATE));
mapzz.put(GET_PRO_CITY, jsonObjsss.getString(GET_PRO_CITY));
profilessstates.add(mapzz);
profilecitis.add(mapzz);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return profilessstates;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
updtfname.setText(usersfname);
updtmail.setText(usersmails);
updtmob.setText(usersmob);
updtaddress.setText(usersaddresss);
updtpin.setText(userszipss);
datestext.setText(usersdobs);
arrprostates = new String[profilessstates.size()];
for (int index = 0; index < profilessstates.size(); index++) {
HashMap<String, String> map = profilessstates.get(index);
arrprostates[index] = map.get(GET_PRO_STATE);
}
adapterprostates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprostates);
statespinner.setAdapter(adapterprostates);
arrprocities = new String[profilecitis.size()];
for (int index = 0; index < profilecitis.size(); index++) {
HashMap<String, String> map = profilecitis.get(index);
arrprocities[index] = map.get(GET_PRO_CITY);
}
adapterprocities = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrprocities);
cityspinner.setAdapter(adapterprocities);
To load all states
class LoadStatess extends
AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
private ProgressDialog pDialog;
private String test;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profiles.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(USER_STATUSS, c.getString(USER_STATUSS));
map.put(PRESET_TITLES, c.getString(PRESET_TITLES));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
// pDialog.dismiss();
arrallstates = new String[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(PRESET_TITLES);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adapterallstates = new ArrayAdapter<String>(
Profiles.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
statespinner.setPrompt("Select State");
statespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spitems = statespinner.getSelectedItem().toString();
System.out.println("PresetEVent selected" + spitems);
new Logincity().execute();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
first screen by default get
then i click to load state it shows
then again i click the only it shows
Put these lines in OnCreate method of your activity.
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, new ArrayList<String>());
statespinner.setAdapter(adapterallstates);
And delete these lines from onPostExecute:
adapterallstates = new ArrayAdapter<String>(Profiles.this.getActivity(),android.R.layout.simple_spinner_dropdown_item, arrallstates);
statespinner.setAdapter(adapterallstates);
And add these lines in for loop of onPostExecute.
adapterallstates.add(map.get(PRESET_TITLES));
adapterprostates.notifyDataSetChanged();
Do this it will work for you.
other one is to,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoadListView();
}
private void LoadListView() {
try {
statespinner.setAdapter(adapterprostates);
} catch (Exception e) {
e.printStacktrace();
}
}
Related
How to access Multiple JSONArrays with Listview?
I have two Listview,I am getting two JSONArray from server,I am getting following response [ [ { "user_status": "1", "pooja_name": "Festival Sevas", "sess_date": "Mon Nov 30 2015", "session_status": "Completed", "message": "What ever message you want" } ], [ { "user_status": "1", "pooja_name": "Pushpalankara Seva", "sess_date": "Tue Dec 15 2015", "session_status": "Pending", "message": "What ever message you want" } ] ] I am able to parse both the arrays,but in my both listview it display Pushpalankara Seva,what i am trying is in my first listview i want to display Pushpalankara Seva and in second Festival Sevas class LoadPoojas extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> { /** * Before starting background thread Show Progress Dialog * */ #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AboutUsFragment.this.getActivity()); pDialog.setMessage("Loading..."); pDialog.setIndeterminate(true); pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress)); pDialog.setCancelable(false); pDialog.show(); } protected ArrayList<HashMap<String,String>> doInBackground(String... args) { ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>(); ArrayList<HashMap<String,String>> upcomingdata = new ArrayList<HashMap<String, String>>(); String jsonStr = sh.makeServiceCall(POOJA_LISTING_URL, ServiceHandler.GET); map = new HashMap<String, String>(); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONArray jsonObj = new JSONArray(jsonStr); // Getting JSON Array node JSONArray pastarray = jsonObj.getJSONArray(0); for (int i = 0; i < pastarray.length(); i++) { JSONObject c = pastarray.getJSONObject(i); // creating new HashMap // adding each child node to HashMap key => value map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME)); } JSONArray upcoming = jsonObj.getJSONArray(1); for (int i = 0; i < upcoming.length(); i++) { JSONObject c = upcoming.getJSONObject(i); // creating new HashMap // HashMap<String, String> upcomingmap = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(POOJA_LISTING_NAME, c.getString(POOJA_LISTING_NAME)); } data.add(map); } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return data; } protected void onPostExecute(ArrayList<HashMap<String,String>> result) { super.onPostExecute(result); /*if(interestaccept == null || interestaccept.length() == 0){ // Toast.makeText(getApplicationContext(), "No response", Toast.LENGTH_SHORT).show(); noacpt.setText(" No Accepted List "); } else { noacpt.setVisibility(View.INVISIBLE); }*/ // dismiss the dialog after getting all albums if (pDialog.isShowing()) pDialog.dismiss(); // updating UI from Background Thread aList = new ArrayList<HashMap<String, String>>(); aList.addAll(result); adapter = new CustomAdapterPooja(getActivity(),result); completedpooja.setAdapter(adapter); adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result); notcompletedpooja.setAdapter(adapterupcoming); adapter.notifyDataSetChanged(); adapterupcoming.notifyDataSetChanged(); completedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { } }); /* upcomingaList = new ArrayList<HashMap<String, String>>(); upcomingaList.addAll(result); adapterupcoming = new CustomAdapterPoojaUpcoming(getActivity(),result); notcompletedpooja.setAdapter(adapterupcoming); adapterupcoming.notifyDataSetChanged(); notcompletedpooja.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { } });*/ } }
I checked you code and found you did mistake in hashmap with same key in both array(inside both For loop). So it overwrite with latest value as per rules of hashmap. Solution : Option 1: Take arraylist of hashmap and create new hashmap each new record. Option 2: Take arraylist of POJO class. Edit : public class UserPOJO { public String user_status; public String pooja_name; public String sess_date; public String session_status; public String message; } Take arraylist of POJO class like below public ArrayList<UserPOJO> userPOJOs = new ArrayList<UserPOJO>(); Now insert data in arraylist from JSONArray.
How can I load json object to Spinner?
I am getting users data from server and load it in spinner till here it works fine, following is my json response { "user_city": "Kolkata", "user_state": "West Bengal", } now it will set to my spinner,now if user want to change state then i have another service for states,there i have all the states,but how to get all states when user click on spinner.. class LoadAllProdetails extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> { private ProgressDialog pDialog; private String test; private JSONObject jsonObjsss; #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Profiles.this.getActivity()); pDialog.setMessage("Please wait.."); pDialog.setIndeterminate(true); pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress)); pDialog.setCancelable(true); pDialog.show(); } protected ArrayList<HashMap<String, String>> doInBackground( String... args) { ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(GET_PRO_DETAILS, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { jsonObjsss = new JSONObject(jsonStr); // state_list = jsonObj.getJSONArray(COUNTRY_LIST); // looping through All Contacts profilessstates=new ArrayList<HashMap<String,String>>(); profilecitis=new ArrayList<HashMap<String,String>>(); if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("0")) { final String msgs=jsonObjsss.getString("message"); System.out.println("Messagessss"+msgs); getActivity().runOnUiThread(new Runnable() { #Override public void run() { Toast.makeText(getActivity(), msgs, Toast.LENGTH_LONG).show(); } }); } else if(jsonObjsss.getString(GET_PRO_USERSTATUS).equals("1")) { HashMap<String, String> mapzz = new HashMap<String, String>(); usersstatus = jsonObjsss.getString(GET_PRO_USERSTATUS); usersfname = jsonObjsss.getString(GET_PRO_FIRSTNAME); usersmails = jsonObjsss.getString(GET_PRO_EMAILS); usersmob = jsonObjsss.getString(GET_PRO_MOBILE); usersdobs = jsonObjsss.getString(GET_PRO_DATES); usersaddresss = jsonObjsss.getString(GET_PRO_ADDRESS); userszipss = jsonObjsss.getString(GET_PRO_ZIP); userstates=jsonObjsss.getString(GET_PRO_STATE); usercitys=jsonObjsss.getString(GET_PRO_CITY); mapzz.put(GET_PRO_STATE, jsonObjsss.getString(GET_PRO_STATE)); mapzz.put(GET_PRO_CITY, jsonObjsss.getString(GET_PRO_CITY)); profilessstates.add(mapzz); profilecitis.add(mapzz); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return profilessstates; } protected void onPostExecute(ArrayList<HashMap<String, String>> result) { super.onPostExecute(result); pDialog.dismiss(); updtfname.setText(usersfname); updtmail.setText(usersmails); updtmob.setText(usersmob); updtaddress.setText(usersaddresss); updtpin.setText(userszipss); datestext.setText(usersdobs); arrprostates = new String[profilessstates.size()]; for (int index = 0; index < profilessstates.size(); index++) { HashMap<String, String> map = profilessstates.get(index); arrprostates[index] = map.get(GET_PRO_STATE); } adapterprostates = new ArrayAdapter<String>( Profiles.this.getActivity(), android.R.layout.simple_spinner_dropdown_item, arrprostates); statespinner.setAdapter(adapterprostates); arrprocities = new String[profilecitis.size()]; for (int index = 0; index < profilecitis.size(); index++) { HashMap<String, String> map = profilecitis.get(index); arrprocities[index] = map.get(GET_PRO_CITY); } adapterprocities = new ArrayAdapter<String>( Profiles.this.getActivity(), android.R.layout.simple_spinner_dropdown_item, arrprocities); cityspinner.setAdapter(adapterprocities); To load all states class LoadStatess extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> { private ProgressDialog pDialog; private String test; #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Profiles.this.getActivity()); pDialog.setMessage("Please wait.."); pDialog.setIndeterminate(true); pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress)); pDialog.setCancelable(true); pDialog.show(); } protected ArrayList<HashMap<String, String>> doInBackground( String... args) { ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response statedata = new ArrayList<HashMap<String, String>>(); String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { jsonObj = new JSONArray(jsonStr); // state_list = jsonObj.getJSONArray(COUNTRY_LIST); // looping through All Contacts for (int i = 0; i < jsonObj.length(); i++) { JSONObject c = jsonObj.getJSONObject(i); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(USER_STATUSS, c.getString(USER_STATUSS)); map.put(PRESET_TITLES, c.getString(PRESET_TITLES)); statedata.add(map); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return statedata; } protected void onPostExecute(ArrayList<HashMap<String, String>> result) { super.onPostExecute(result); pDialog.dismiss(); arrallstates = new String[statedata.size()]; for (int index = 0; index < statedata.size(); index++) { HashMap<String, String> map = statedata.get(index); arrallstates[index] = map.get(PRESET_TITLES); } // pass arrConuntry array to ArrayAdapter<String> constroctor : adapterallstates = new ArrayAdapter<String>( Profiles.this.getActivity(), android.R.layout.simple_spinner_dropdown_item, arrallstates); statespinner.setAdapter(adapterallstates); statespinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { #Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spitems = statespinner.getSelectedItem().toString(); System.out.println("PresetEVent selected" + spitems); new Logincity().execute(); } #Override public void onNothingSelected(AdapterView<?> adapterView) { } }); } }
XML file: <Spinner android:id="#+id/Spinner01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> Java file: public class SpinnerExample extends Activity { private String[] arraySpinner; #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //json to list ArrayList<String> list = new ArrayList<String>(); JSONArray jsonArray = (JSONArray)jsonObject; if (jsonArray != null) { int len = jsonArray.length(); for (int i=0;i<len;i++){ list.add(jsonArray.get(i).toString()); } } //add list to spinner Spinner s = (Spinner) findViewById(R.id.Spinner01); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); s.setAdapter(adapter); } }
After storing value in preference it is not setting in textview
I am android developer. I am creating one app, in my app I am using json parsing to get state name, so when user click on texTextViewtview("Select State"), the alert dialog with all the state name will appear. Then I can select any state name, and it will set in my TextView and also storing in preference. Till here it works well, but the issue is if I close the app and again open the which I have set in my TextView is gone and again it shows "Select State".. Any help would be appreciated.. Following is my snippet code MainActivity.java #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //spcountry=(TextView)rootView.findViewById(R.id.spinnercountry); spstate=(TextView)findViewById(R.id.feedbackspinnerstates); spcity=(TextView)findViewById(R.id.feedbackspinnercitys); new LoadAllStates().execute(); } class LoadAllStates extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> { #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait.."); pDialog.setIndeterminate(true); // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress)); pDialog.setCancelable(true); pDialog.show(); } protected ArrayList<HashMap<String, String>> doInBackground( String... args) { ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response statedata = new ArrayList<HashMap<String, String>>(); String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); state_list = jsonObj.getJSONArray(COUNTRY_LIST); // looping through All Contacts for (int i = 0; i < state_list.length(); i++) { JSONObject c = state_list.getJSONObject(i); // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); // adding each child node to HashMap key => value map.put(STATE_SLG, c.getString(STATE_SLG)); map.put(STATE_ID, c.getString(STATE_ID)); map.put(STATE_NAME, c.getString(STATE_NAME)); statedata.add(map); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return statedata; } protected void onPostExecute(ArrayList<HashMap<String, String>> result) { super.onPostExecute(result); pDialog.dismiss(); arrallstates = new String[statedata.size()]; for (int index = 0; index < statedata.size(); index++) { HashMap<String, String> map = statedata.get(index); arrallstates[index] = map.get(STATE_NAME); } // pass arrConuntry array to ArrayAdapter<String> constroctor : adapterallstates = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, arrallstates); spstate.setOnClickListener(new OnClickListener() { #Override public void onClick(View w) { new AlertDialog.Builder(MainActivity.this) .setTitle("Select") .setAdapter(adapterallstates, new DialogInterface.OnClickListener() { #Override public void onClick( DialogInterface dialog, int which) { test=adapterallstates .getItem(which).toString(); SharedP.setStringToSharedPrefsForKey("MyKey", test, MainActivity.this); System.out.println("whts in pref"+SharedP.setStringToSharedPrefsForKey("MyKey", test, MainActivity.this)); System.out.println("whts in pref get"+SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this)); storeds=SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this); Log.d("Tag", SharedP.getStringFromSharedPrefsForKey("MyKey", MainActivity.this)); spstate.setText(storeds); if( spstate.getText().length() != 0) { System.out.println("NotEMpty"); } else { System.out.println("EMpty"); } try { statename = state_list .getJSONObject(which) .getString("state_slug"); stnm = state_list .getJSONObject(which) .getString(STATE_NAME); Log.d("Response statenm: ", "> " + statename); // new LoadAllStatesCity() //.execute(); // Toast.makeText(getActivity(), // statename, // Toast.LENGTH_LONG).show(); } catch (JSONException e) { // TODO Auto-generated catch // block e.printStackTrace(); } dialog.dismiss(); } }).create().show(); } }); } }
Please look at the below code : Setting Value : SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("yourtextvalueKey", "yourvalue"); editor.commit(); Getting value : SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String text= prefs.getString("yourtextvalueKey", null); if(text != null){ textview.setText(text); } Note : MY_PREFS_NAME : It's preference key. e.g "myprefs" both will be same while setting and getting value by preferences. And try to declare your your preference globally and initialize it in onCreate() method. Hope it will help you.
Android implement infinite scroll using pagination from API
I have an API with a pagination scheme, like that: -meta: { -pagination: { total: 100 count: 20 per_page: 20 current_page: 1 total_pages: 5 -links: { next: "http://dev.app/api/posts?page=2" } } } I'm trying to find a way to implement that on my android app using volley and infinite scroll, the app has to read the json pagination from the API and scroll down to 20 items and than autoload to the next page, the problem is that when I get to "page=2" and I hit LoadMore button again it still getting the page 2 and not page 3, I mean, the current page is always 1, I don't know why this is happening, what I tried to do is: public class MainActivity extends ListActivity { ConnectionDetector cd; AlertDialogManager alert = new AlertDialogManager(); //Progress Dialog private ProgressDialog pDialog; //make json parser Object JSONParser jsonParser = new JSONParser(); ArrayList<HashMap<String, String>> restaurant_list; //Restaurant Json array JSONArray restaurants = null; JSONObject pagination = null; JSONObject link = null; private String url_posts = "http://dev.app/api/posts"; //Flag for current page private String nPage; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cd = new ConnectionDetector(getApplicationContext()); //Check for Internet Connection if (!cd.isConnectingToInternet()) { //Internet connection not present alert.showAlertDialog(MainActivity.this, "Internet Connection Error", "Please Check Your Internet Connection"); //stop executing code by return return; } restaurant_list = new ArrayList<HashMap<String, String>>(); new LoadRestaurants().execute(); Button btnLoadMore = new Button(MainActivity.this); btnLoadMore.setText("Show More"); getListView().addFooterView(btnLoadMore); btnLoadMore.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { url_posts = nPage; new LoadRestaurants().execute(); } }); } class LoadRestaurants extends AsyncTask<String, String, String> { //Show Progress Dialog #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Loading All Restaurants..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } #TargetApi(Build.VERSION_CODES.KITKAT) protected String doInBackground(String... arg) { //building parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jsonParser.makeHttpRequest(url_posts, "GET", params); try { restaurants = json.getJSONArray("data"); JSONObject meta = json.getJSONObject("meta"); pagination = meta.getJSONObject("pagination"); link = pagination.getJSONObject("links"); nPage = link.getString("next"); if (restaurants != null) { //loop through all restaurants for (int i = 0; i < restaurants.length(); i++) { JSONObject c = restaurants.getJSONObject(i); //Creating New Hashmap HashMap<String, String> map = new HashMap<String, String>(); //adding each child node to Hashmap key map.put("id", c.getString("id")); map.put("look1", c.getString("look1")); map.put("look2", c.getString("look2")); map.put("comment", c.getString("comment")); //adding HashList to ArrayList restaurant_list.add(map); } } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { //dismiss the dialog pDialog.dismiss(); //Updating UI from the Background Thread runOnUiThread(new Runnable() { #Override public void run() { ListAdapter adapter = new SimpleAdapter( MainActivity.this, restaurant_list, R.layout.feed_item, new String[]{ "id", "look1", "look2", "comment"}, new int[]{ R.id.profilePic, R.id.name, R.id.txtUrl}); setListAdapter(adapter); ListView lv = getListView(); int currentPosition = lv.getFirstVisiblePosition(); lv.setSelectionFromTop(currentPosition + 1, 1); } }); } } }
Fixed Tab + Swipe with ListView
I'm doing an app that has mutiple tab and for each tab has its own activity. after putting the code to load the list on one activity; still listview is not visible at all. here is my code, somebody please help: public class BillsActivity extends ListActivity { private ProgressDialog pDialog; String mUrl = BayadCenterConstants.BAYAD_URL_BILLERS; JSONParsers jsonParser = new JSONParsers(); ArrayList<HashMap<String, String>> billerList; JSONArray billers = null; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tab_child_bills); /* * Check network connection here */ billerList = new ArrayList<HashMap<String, String>>(); new LoadBillers().execute(); } class LoadBillers extends AsyncTask<String, String, String> { #Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(BillsActivity.this); pDialog.setMessage("Downlaoding list ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } protected String doInBackground(String... args) { List<NameValuePair> params = new ArrayList<NameValuePair>(); String json = jsonParser.getBillers(mUrl, params); Log.d("Billers JSON: ", "> " + json); try { billers = new JSONArray(json); if (billers != null) { for (int i = 0; i < billers.length(); i++) { JSONObject c = billers.getJSONObject(i); String id = c.getString("bid"); String name = c.getString("name"); String status = c.getString("status"); String date_added = c.getString("date_added"); HashMap<String, String> map = new HashMap<String, String>(); map.put("bid", id); map.put("name", name); map.put("status", status); map.put("date_added", date_added); billerList.add(map); } }else{ Log.d("Billers: ", "null"); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); runOnUiThread(new Runnable() { public void run() { ListAdapter adapter = new SimpleAdapter( BillsActivity.this, billerList, R.layout.tab_child_bills_list_row, new String[] { "bid", "name", "status", "date_added" }, new int[] { R.id.txtBillerID, R.id.txtBillerName, R.id.txtBillerStatus, R.id.txtBillerDateAdded }); setListAdapter(adapter); } }); } } this activity is just part of an activity that holds then in tab+swipe manner. did i miss something with my code?