ArrayAdapter : Json data to be sent to spinner - android

Hi I have created an activity which pulls data from json format text and displays in a spinner view. But im a little confused with the last part. The contactList is a ArrayList type, ArrayAdapter is not accepting contactList as its arugument.
Is
Here's my code
public class RegisterForEventActivity extends Activity {
private static String url = "http://10.0.2.2/Contacts.txt";
private static final String TAG_NAME = "name";
private static final String TAG_CONTACTS = "contacts";
JSONArray jsonArray = null;
Spinner areaspinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] array_spinner = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, contactList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaspinner.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

This is because you are passing a list of HashMap, and not an array of String. Make an array of String, add your contact data in it and pass it to the array.
instead of using this
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
use this
ArrayList<String> contactList = new ArrayList<String>();

Yes, I figured it out!
sp=(Spinner)findViewById(R.id.spinner1);
// Hashmap for ListView
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
System.out.println("Hello");
try {
// Getting Array of Contacts
jsonArray = json.getJSONArray(TAG_CONTACTS);
final String[] items = new String[jsonArray.length()];
// looping through All Contacts
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
items[i]=c.getString(TAG_NAME);
System.out.println("Hello events "+items);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to grouping data by date display in listview (data based on parse json)?

I wanna grouping my data such as an schedule by date or week where i display in listview.
I hope the result like this :
here my activity to show the data based on json parse :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tampil_semua_pgw);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
}
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(konfigurasi.TAG_ID);
String nama = jo.getString(konfigurasi.TAG_NAMA);
String pyg = jo.getString(konfigurasi.TAG_PENYELENGGARA);
String tmpt = jo.getString(konfigurasi.TAG_TEMPAT);
String tgl = jo.getString(konfigurasi.TAG_TGL);
String jam = jo.getString(konfigurasi.TAG_JAM);
String email = jo.getString(konfigurasi.TAG_EMAIL);
HashMap<String,String> employees = new HashMap<>();
employees.put(konfigurasi.TAG_ID,id);
employees.put(konfigurasi.TAG_NAMA,nama);
employees.put(konfigurasi.TAG_PENYELENGGARA,pyg);
employees.put(konfigurasi.TAG_TEMPAT,tmpt);
employees.put(konfigurasi.TAG_TGL,tgl);
employees.put(konfigurasi.TAG_JAM,jam);
employees.put(konfigurasi.TAG_EMAIL,email);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new MySimpleArrayAdapter(this, list);
listView.setAdapter(adapter);
}
And here my custom adapter :

how to parse JSONArray in android NullPointerException

I want to parse jsonObject passed by another activity
intent.putextra("result", json.toString());
It shows everything right with name, branch and session. but it shows NullPointerException while fetching array. at here
mSubList.add(map);
this array has 6 rows.
this is my code. please tell me exactly where Im wrong.
JSONObject json;
ListView sub_list;
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mSubList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
name = (TextView)findViewById(R.id.name_roll);
branch= (TextView)findViewById(R.id.branchname);
session = (TextView)findViewById(R.id.Session);
sub_list = (ListView)findViewById(R.id.sub_list);
try {
json = new JSONObject(getIntent().getStringExtra("result"));
name.setText(json.getString("REGNO")+" - "+json.getString("STUDENTNAME"));
branch.setText(json.getString("BRANCHNAME"));
session.setText(json.getString("SESSIONNAME"));
mComments = json.getJSONArray("DATA");
// looping through all subjects according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String code = c.getString("CCODE");
String subject = c.getString("COURSENAME");
String passfail = c.getString("PASSFAIL");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put("CCODE", code);
map.put("COURSENAME", subject);
map.put("PASSFAIL", passfail);
// adding HashList to ArrayList
mSubList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mSubList,
R.layout.singlesubject, new String[] { "CCODE", "COURSENAME",
"PASSFAIL" }, new int[] { R.id.sub_id, R.id.sub_name,R.id.sub_res });
sub_list.setAdapter(adapter);
}catch(Exception e){
e.printStackTrace();
}
}
}
if I want to change each listitem background(R.layout.singlesubject) if "PASSFAIl"=P then Green color else Red color. then what changes i have to do ?
mSubList.add(map);
this line of code is failing because you do not initialize the array before adding the map
You can initialize it by using...
mSubList = new ArrayList<Hashmap<String, String>>();
init your mSubList before add item
mSubList = new ArrayList<HashMap<String, String>>();
I think you forgot to initialize mSubList before adding data to it:
mSubList = new ArrayList<HashMap<String, String>>();

How to display image in listview from json dynamically

I want to list text and image from json which is placed in particular url
I have successively displayed textview but how to display image my code is
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "***MY URL***";
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_URL = "hosting_thumbnail_url";
// contacts JSONArray
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_jsonparsing);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_PRICE);
//String image1 = c.getString( TAG_URL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, email);
//map.put(TAG_URL, image1);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_PRICE }, new int[] {
R.id.name, R.id.email });
setListAdapter(adapter);
}
}
i want listview like this "http://pic002.cnblogs.com/images/2012/372551/2012021011374176.jpg"
You will need to write a custom list adapter. Google for "android custom listadapter image". The first hit is this one, which looks like a decent example.
As SimonSays said, you have to implement your own ListView adapter class and its getView() method.
If you plan to obtain these JSON objects dynamically in ListView I strongly recommend to use some Thread mechanism, that would set data from that JSON object to ListView immediately when it's obtained - i.e. AsyncTask

Android: How to sort data for ListView?

I have some JSON data I am pulling down from a server. One of the fields in this data is a distance value. I need to have the data sorted by distance from lowest to highest in the ListView. I am not sure how to go about doing this?
Any help appreciated.
This is my code to grab the data not sure how to get it sorted properly?
// Hashmap for ListView
ArrayList<HashMap<String, String>> bathroomList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_search);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
bathrooms = json.getJSONArray(TAG_BATHROOMS);
// looping through All Contacts
for(int i = 0; i < bathrooms.length(); i++){
JSONObject c = bathrooms.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String access = c.getString(TAG_ACCESS);
String city = c.getString(TAG_CITY);
String comment = c.getString(TAG_COMMENT);
String directions = c.getString(TAG_DIRECTIONS);
String name = c.getString(TAG_NAME);
String street = c.getString(TAG_STREET);
String bathroomtype = c.getString(TAG_BATHROOMTYPE);
String distance = c.getString(TAG_DISTANCE);
String distanceTrimmed = distance.substring(0,4) + " " + "miles away";
String avail = c.getString(TAG_AVAIL);
String country = c.getString(TAG_COUNTRY);
String state = c.getString(TAG_STATE);
String postal = c.getString(TAG_POSTAL);
//System.out.println(name);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_ACCESS, access);
map.put(TAG_CITY, city);
map.put(TAG_COMMENT, comment);
map.put(TAG_DIRECTIONS, directions);
map.put(TAG_NAME, name);
map.put(TAG_STREET, street);
map.put(TAG_BATHROOMTYPE, bathroomtype);
map.put(TAG_DISTANCE, distanceTrimmed);
map.put(TAG_AVAIL, avail);
map.put(TAG_COUNTRY, country);
map.put(TAG_STATE, state);
map.put(TAG_POSTAL, postal);
// adding HashList to ArrayList
bathroomList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, bathroomList,
R.layout.list_item,
new String[] { TAG_ID, TAG_NAME, TAG_STREET, TAG_CITY, TAG_STATE, TAG_POSTAL,TAG_COUNTRY, TAG_DISTANCE, TAG_DIRECTIONS, TAG_COMMENT, TAG_AVAIL, TAG_BATHROOMTYPE, TAG_ACCESS}, new int[] {
R.id.key,R.id.name, R.id.street, R.id.city, R.id.state, R.id.postal,R.id.country, R.id.distance, R.id.directions, R.id.comments, R.id.availability, R.id.bathroomtype, R.id.access });
setListAdapter(adapter);
Sort the list using Collections.sort() with a custom comparator.
Collections.sort(bathroomList, new Comparator<HashMap<String, String>>()
{
#Override
public int compare(HashMap<String, String> a, HashMap<String, String> b)
{
return a.get(TAG_DISTANCE).compareTo(b.get(TAG_DISTANCE));
}
});
same problem with mine but I've get it work now, Thanks to #rusmus. Take a Look Sorting Double Data (distance) on ListView
Try this code:
Collections.sort(bathroomList, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> o1,
HashMap<String, String> o2) {
return Double.compare(Double.parseDouble(o1.get(TAG_DISTANCE)), Double.parseDouble(o2.get(TAG_DISTANCE))); // error
}
});

How to display the parsed JSON data in android

I have parsed the JSON data and storing the parsed JSON data into ArrayList HashMap with the key value ,when I want to display the parsed data I am getting only the last value of the parsed Data rest all data are not displayed for reference
public HashMap<String,String> map = new HashMap<String, String>();
create HASHmap then arraylist
public static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
void parsing(JSONObject json)
{
String id="";
String countryn="";
try
{
countryobj = json.getJSONArray("country_details");
for(int i = 0;i<countryobj.length(); i++)
{
JSONObject items = countryobj.getJSONObject(i);
Log.e("i","value==="+i);
if(items.has("countryid"))
{
id = items.getString("countryid");
map.put("countryid",id);
Log.e("id","valueID==="+id);
}
if(items.has("country"))
{
countryn= items.getString("country");
map.put("country",countryn);
Log.e("counyrt","valueName==="+countryn);
}
contactList.add(i,map);
Log.e("lisvaluet","val--"+i +contactList.get(i));
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
in Log I am getting only 08-20 12:13:45.830: E/--ID---(654): value--{countryid=275, country=Palestinian Territory} with 269 times can any help me out where I am doing wrong in storing the parsed data , I am stuck here.
Check this.
private JSONObject[] items;
JSONArray countryobj = json.getJSONArray("country_details");
items = new JSONObject[countryobj.length()];
for(int i=0, i < countryobj.length(); i++)
{
items[i] = countryobj.optJSONObject(i);
id = items[i].getString("countryid");
map.put("countryid",id);
countryn= items[i].getString("country");
map.put("country",countryn);
contactList.add(i,map);
}

Categories

Resources