Error when selecting an item in my spinner - android

I am getting an error java.lang.String cannot be cast to java.util.HashMap when i select a data on my spinner. I retrieve my data in my spinner from my database. Im am trying to have just only 1 class, when i select a item on my spinner it checks the id in my database to show filter and show only the selected id
Here is my spinner select
ArrayList<HashMap<String,String>> list1 = new ArrayList<>();
try
{
JSONArray JA = new JSONArray(result);
JSONObject json;
s_name = new String[JA.length()];
s_gender = new String[JA.length()];
for(int i = 0; i<JA.length(); i++)
{
json = JA.getJSONObject(i);
s_gender[i] = json.getString("s_gender");
s_name[i] = json.getString("s_name");
}
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner_fn();
ArrayList<HashMap<String,String>> spinner = new ArrayList<Object>(Games.this, layout.simple_spinner_dropdown_item, s_name);
spinner1.setAdapter((SpinnerAdapter) spinner);
spinner1.setSelection(0);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = null;
switch (position) {
case 1:
intent = new Intent(getApplication(), Basketball.class);
HashMap<Object, Object> map = (HashMap)parent.getItemAtPosition(position);
String news_id = map.get(Config.TAG_news_id).toString();
String title = map.get(Config.TAG_title).toString();
String content = map.get(Config.TAG_content).toString();
String n_date = map.get(Config.TAG_n_date).toString();
intent.putExtra(Config.News_id,news_id);
intent.putExtra(Config.Title,title);
intent.putExtra(Config.Content,content);
intent.putExtra(Config.N_date,n_date);
startActivity(intent);
break;
I am getting the error here saying in arraylist cannot be applied to java.lang.string
(Games.this, layout.simple_spinner_dropdown_item, s_name);
list1.add("All");
for(int i = 0; i<s_name.length; i++)
{
list1.add(s_name[i] + " "+s_gender[i]);
}

list1.add(s_name[i] + " "+s_gender[i]);
here is an error, as list1 is ArrayList of HASHMAP (you have a lot of hashmaps in one arraylist), and you've tried to add usual String to this list. May be you wanted the next:
for(int i = 0; i<s_name.length; i++)
{
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(s_name[i], s_gender[i]);
list1.add(hashMap);
}

//Remove this line
list1.add("All");
use this.
HashMap<String,String> stringHashMap=new HashMap<>();
for(int i = 0; i<s_name.length; i++)
{
stringHashMap.put(s_name[i],s_gender[i]);
list1.add(stringHashMap);
}
ArrayList<String> spinnerArray=new ArrayList<>();
Map<String, String> map = stringHashMap;
for (Map.Entry<String, String> entry : map.entrySet()) {
spinnerArray.add(entry.getKey());
}
ArrayAdapter<String> spinner = new ArrayAdapter<String>(Games.this, layout.simple_spinner_dropdown_item, spinnerArray);
spinner1.setAdapter(spinner);
spinner1.setSelection(0);

Related

parse JsonArray in android

How to parse this jsonarray "Images" ??
I parse this json ,, but i can't get "Images"
the Jsonarray "data" inside it elements , inside every element array of images >>>>
this is the response
this is my code
JSONObject responseObject = new JSONObject(response);
JSONArray newsJsonArray = responseObject.getJSONArray("data");
final List <AndroidVersion> newsList = new ArrayList <AndroidVersion>();
newsImages = new ArrayList<String>();
newsids = new ArrayList<String>();
newsnames = new ArrayList<String>();
newshotelsid = new ArrayList<String>();
newscontents = new ArrayList<String>();
newstimesto = new ArrayList<String>();
newscost = new ArrayList<String>();
newstimesfrom = new ArrayList<String>();
newscountry = new ArrayList<String>();
newscity = new ArrayList<String>();
newstype = new ArrayList<String>();
newsImages = new ArrayList<String>();
for (int j = 0; j < newsJsonArray.length(); j++) {
AndroidVersion news = new AndroidVersion();
if (newsJsonArray.getJSONObject(j).has("id")) {
newsids.add(newsJsonArray.getJSONObject(j).getString("id"));
}
if (newsJsonArray.getJSONObject(j).has("name")) {
news.setName(newsJsonArray.getJSONObject(j).getString("name"));
newsnames.add(newsJsonArray.getJSONObject(j).getString("name"));
}
if (newsJsonArray.getJSONObject(j).has("desc")) {
news.setdesc(newsJsonArray.getJSONObject(j).getString("desc")
.replaceAll("<p>", "").replaceAll("<\\/p>\\r\\n", "").replaceAll(" ", ""));
newscontents.add(newsJsonArray.getJSONObject(j).getString("describtion"));
}
if (newsJsonArray.getJSONObject(j).has("country")) {
news.setcountry(newsJsonArray.getJSONObject(j).getString("country"));
newscountry.add(newsJsonArray.getJSONObject(j).getString("country"));
}
if (newsJsonArray.getJSONObject(j).has("city")) {
news.setcity(newsJsonArray.getJSONObject(j).getString("city"));
newscity.add(newsJsonArray.getJSONObject(j).getString("city"));
}
if (newsJsonArray.getJSONObject(j).has("date_from")) {
news.setdate_from(newsJsonArray.getJSONObject(j).getString("date_from"));
newstimesfrom.add(newsJsonArray.getJSONObject(j).getString("date_from"));
}
if (newsJsonArray.getJSONObject(j).has("date_to")) {
news.setdate_to(newsJsonArray.getJSONObject(j).getString("date_to"));
newstimesto.add(newsJsonArray.getJSONObject(j).getString("date_to"));
}
if (newsJsonArray.getJSONObject(j).has("num persons")) {
news.sethotel_id(newsJsonArray.getJSONObject(j).getString("num persons"));
newshotelsid.add(newsJsonArray.getJSONObject(j).getString("num persons"));
}
if (newsJsonArray.getJSONObject(j).has("price")) {
news.setprice(newsJsonArray.getJSONObject(j).getString("price"));
newscost.add(newsJsonArray.getJSONObject(j).getString("price"));
}
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
newsList.add(news);
}
I would highly recommend using Gson to parse it.
Create a response object with structure matching the json response. Then you can use the single object without having to create it down into parts.
Change this part:
if (newsJsonArray.getJSONObject(j).has("images")) {
news.setImage(newsJsonArray.getJSONObject(j).getString("images"));
newsImages.add(newsJsonArray.getJSONObject(j).getString("images"));
}
to:
if(newsJsonArray.getJSONObject(j).getJSONArray("images") != null) {
JSONArray jArray = newsJsonArray.getJSONObject(j).getJSONArray("images");
for (int k=0; k<jArray.length(); k++) {
news.setImage(jArray.getString(k));
newsImages.add(jArray.getString(k));
}
}
You can use direct string object from JSONArray like below:
JSONArray array = object.getJSONArray("images");
for (int i = 0; i < array.length(); i++) {
String image = array.getString(i);
}

Android get the Key in Hashmap in Arraylist within Listview CHOICE_MODE_MULTIPLE

I parse json data and display it in listview with CHOICE_MODE_MULTIPLE. I trying to get the key of a Hashmap in my case but I only manage to get the value.
Json data
57->Steak Doness
58->Size
59->Cooking Method
63->Coldness
Here is the coding
String option_data = jsonObject.getString("option_data");
JSONObject jsonObject1 = new JSONObject(option_data);
Iterator<String> iterator = jsonObject1.keys();
ArrayList arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = null;
while (iterator.hasNext()) {
String id = iterator.next();
String name = jsonObject1.getString(id);
map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
arrayList.add(name);
}
ArrayAdapter adapter = new ArrayAdapter<String>(item_add.this, android.R.layout.simple_list_item_multiple_choice, arrayList);
final ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String selected = "";
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for (int i = 0; i < listView.getCount(); i++) {
if (sparseBooleanArray.get(i)) {
selected += listView.getItemAtPosition(i).toString() + ",";
}
}
Log.d("selected", selected);
}
});
With the logcat, it shows
D/selected: Steak Doness,Size,
However, what I want to get is the Key in Hashmap which means "id" when click the button . Anyone knows how to do it?
Use the following way to iterate and find values of keys
HashMap <String,String> mapOne= new HashMap();
mapOne.put("1","1value");
mapOne.put("2","2value");
mapOne.put("3","3value");
for(Map.Entry<String, String> mapEntry : mapOne.entrySet()){
if (mapEntry.getValue().equals("3value")) {
//System.out.println(mapEntry.getKey());
Log.d("selected", mapEntry.getKey());
}
}

Android get elements from json array

I'm trying to get elements from my json array.
this is my json response:
{"IDs":["635426812801493839","635429094450867472","635433640807558204"]}
This is what I've tried so far:
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
JSONObject obj = a.getJSONObject(i);
stringArray.add(obj.toString());
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());
But I'm getting empty list. What is wrong with my code? Any help will be truly appreciated. Thanks.
The for loop should be
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
your the JSONArray contains already string
JSONObject obj = a.getJSONObject(i);
replace with
String str = a.getString(i);
Use this
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());

How to set json data to list view?

I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

Get hashmap out of an Array with Hashmap value X

I have an arraylist with multiple hashmaps that contains information that comes from a sql database
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
This arraylist will eventually fill my listview with items (names of people).
When I click on one item I want to send all of the content of that hashmap to another page.
For example:
John <
Now I want to send the hashmap with all the information of John to another android page.
How do I get that information out of the hashmap?
This is my code:
public class Contactenlijst extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactview);
ListView lv;
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
String[] from = new String[] {"naam"};
int[] to = new int[]{R.id.naam};
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// Get the data (see above)
JSONObject json = Database
.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try {
JSONArray contactinfo = json.getJSONArray("contactlijst");
// Loop the Array
for (int i = 0; i < contactinfo.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
//array for view
ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < mylist.size(); i++){
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("naam", (mylist.get(i).get("voornaam")+" "+(mylist.get(i).get("achternaam"))));
mylist2.add(map2);
}
try{
lv.setAdapter(new SimpleAdapter(this, mylist2, R.layout.list_item, from, to));
}catch (Exception e){Log.d("test1","test2");}
//onclick stuur array naar contactinfo
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String text = ((TextView) view).getText().toString();
Intent i = new Intent(Contactenlijst.this, Contactinfo.class);
String uittekst[] = text.split(" ");
String voornaam = uittekst[0].toString();
String achternaam = uittekst[1].toString();
startActivity(i);
}
});
}
}
So it all has to happen under "String achternaam = uittekst[1].toString();"
for(Hashmap<String, String> map: mylist) {
for(Entry<String, String> mapEntry: map) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
}
}

Categories

Resources