java.lang.IndexOutOfBoundsException: Invalid index 8, size is 0 - android

When I drag list up and try to show all list Item that time it gives me error like this.
and this is my AsyncTask which working in background.
please give some error free Hints....
This asyncTask is called by services in a few seconds.
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
String url = args[0];
rssItems = rssParser.getRSSFeedItems(url);
FeedDBHandler rssDb = new FeedDBHandler(getApplicationContext());
// RSSItem rssItem;
rssItems.size();
Log.i("size", "size:" + rssItems.size());
for (RSSItem item : rssItems) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// Truncating description
String description = item.getDescription();
if (description.length() > 100)
description = description.substring(3, 97) + "..";
// Store in database
rssItem = new RSSItem(item.getTitle(), item.getLink(),
item.getCategory(), description, item.getPubdate());
// check if not exist -notify and insert
if (!rssDb.isExistItem(item.getLink())) {
createNotification(item.getTitle());
rssDb.addFeed(rssItem);
}
createNotification(item.getTitle());
if (map != null) {
map.put(TAG_TITLE, item.getTitle());
map.put(TAG_LINK, item.getLink());
map.put(TAG_CATEGORY, item.getCategory());
map.put(TAG_DESRIPTION, description);
map.put(TAG_PUB_DATE, item.getPubdate());
rssItemList.add(map);
}
}
return rssItemList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> rssItemList) {
ListAdapter adapter = new SimpleAdapter(AndroidRSSReaderList.this,
rssItemList, R.layout.rss_item_list_row,
new String[] { TAG_LINK, TAG_TITLE, TAG_DESRIPTION,
TAG_PUB_DATE }, new int[] { R.id.page_url,
R.id.title, R.id.link, R.id.pub_date });
// updating listview
lv.setAdapter(adapter);
lv.deferNotifyDataSetChanged();
// lv.onDataSetChanged();
// dismiss the dialog after getting all products
// pDialog.dismiss();
}
}
Thanks in Advance...

#Override
protected void onPreExecute() {
super.onPreExecute();
rssItemList.clear();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
// updating UI from Background Thread
FeedDBHandler rssDb = new FeedDBHandler(getApplicationContext());
// listing all RSSItems from SQLite
List<RSSItem> rssList = rssDb.getAllItems();
// loop through each RSSItem
for (int i = 0; i < rssList.size(); i++) {
RSSItem s = rssList.get(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_TITLE, s.getTitle());
map.put(TAG_LINK, s.getLink());
map.put(TAG_CATEGORY, s.getCategory());
map.put(TAG_DESRIPTION, s.getDescription());
map.put(TAG_PUB_DATE, s.getPubdate());
// adding HashList to ArrayList
rssItemList.add(map);
}
return rssItemList;
}
#Override
protected void onPostExecute(final ArrayList<HashMap<String, String>> rssItemList) {
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
AndroidRSSReaderList.this, rssItemList,
R.layout.rss_item_list_row, new String[] {
TAG_LINK, TAG_TITLE, TAG_PUB_DATE,
TAG_DESRIPTION }, new int[] {
R.id.page_url, R.id.title, R.id.pub_date,
R.id.link });
// updating listview
setListAdapter(adapter);
}
});
}
I have solved this questions by some changes...

Related

Android convert JSONObject to HashMap and display in ListView with SimpleAdapter

I try to search converting JSONObject to HashMap but most of the results are for Java not Android. Hence, I hope someone can share if you have experience in doing this before.
listview_with_simpleAdapter_and_hashmap.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
String[] food_id= new String[]{"1", "2", "3"};
String[] food_name = new String[]{"apple", "orange", "banana"};
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 3; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("ID", food_id[i]);
hm.put("Name", food_name[i]);
aList.add(hm);
}
String[] from = {"ID", "Name"};
int[] to = {R.id.text_id, R.id.text_name};
SimpleAdapter adapter = new SimpleAdapter(this, aList, R.layout.list_item, from, to);
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
this file is working fine and simply display 2 columns in each row;
json.java
TextView mTxtDisplay;
String url = "http://192.168.1.103/web_service/omg.php/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxtDisplay = (TextView) findViewById(R.id.tv);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mTxtDisplay.setText(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);
192.168.1.103/web_service/omg.php/
{
"32":"Western Food",
"35":"Japanese Food",
"37":"Italian Food"
}
JSON is working fine as well. The format is exactly the same as the ListView data -> ID and Name.
So my question is how to convert the JSONObject in omg.php to listview_with_simpleAdapter_and_hashmap.java ? I just need a simple example.
You could do something like this:
ListView listView = (ListView) findViewById(R.id.listView);
// ...
#Override
public void onResponse(JSONObject response) {
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
Iterator<String> iterator = response.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String value = response.getString(key);
HashMap<String, String> map = new HashMap<>();
map.put(KEY_ID, key);
map.put(KEY_NAME, value);
list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
if(list.size() > 0) {
String[] from = {KEY_ID, KEY_NAME};
int[] to = {R.id.text_id, R.id.text_name};
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.list_item, from, to);
listView.setAdapter(adapter);
}
}
try this code to convert Jsonobject to hashmap
Map<String, String> params = new HashMap<String, String>();
try
{
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = (String) keys.next();
String value = jsonObject.getString(key);
params.put(key, value);
}
}
catch (Exception xx)
{
xx.toString();
}

How to load replace json values in spinner?

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();
}
}

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);
}
}

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?

Android ListView with or without Images

I am trying to create a listView where JSON data is pulled into a SimpleAdapter, but what i can figure out is how to hide the Rank image if it is returned null.
private class LoadDataTask extends AsyncTask<Void, Void, String[]> {
ProgressDialog Dialog = new ProgressDialog(Post.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
mylist.clear();
Dialog.setMessage("Loading Posts...");
Dialog.setCancelable(true);
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
preferences = PreferenceManager.getDefaultSharedPreferences(Post.this);
String userID = preferences.getString("userID", "n/a");
String TID = Post.this.getIntent().getExtras().getString("id");
try{
JSONObject json = JSONfunctions.getJSONfromURL(Constants.BASE_URL+"/posts.php?user="+userID+"&postID="+TID);
JSONArray users = json.getJSONArray("users");
for(int i=0;i<users.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("pid", e.getString("poster_id"));
map.put("id", e.getString("post_id"));
map.put("Forum", e.getString("forum_id"));
map.put("Topic", e.getString("topic_id"));
map.put("Name", e.getString("poster_name"));
map.put("Text", string);
map.put("IP", e.getString("poster_ip"));
map.put("Status", e.getString("poster_status"));
map.put("Rank", e.getString("prank"));
map.put("Time", e.getString("poster_time"));
map.put("active", e.getString("active"));
map.put("posterisimage", e.getString("posterisimage"));
map.put("posterimage", e.getString("posterimage"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "Time", "Text", "Name" ,"Rank"}, <==Hide Rank if returned null ???
new int[] { R.id.item_date, R.id.item_subtitle , R.id.item_title, R.id.item_image});
((SimpleAdapter) adapter).notifyDataSetChanged();
setListAdapter(adapter);
Dialog.dismiss();
super.onPostExecute(result);
}
}
Can someone show or point in me the right direction.
You can write your own ViewBinder from SimpleAdapter:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() != R.id.item_image)
return false;
if(data == null) {
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
return false;
}
});
This ViewBinder is very primitive. I recommend customizing it to your particular layout.

Categories

Resources