In Android I am fetching json data from web.I the list is like {Name,dial,code}
I have this
countryinfo = new ArrayList<CountryInfo>();
Countrylist = new ArrayList<String>();
try {
for (String line : result) {
jsonarray= new JSONArray(line);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
CountryInfo conpop = new CountryInfo();
conpop.setName(jsonobject.optString("Name"));
conpop.setIso(jsonobject.optString("dial"));
conpop.setItu(jsonobject.optString("code"));
countryinfo.add(conpop);
Countrylist.add(jsonobject.optString("Name"));
}
}
} catch (Exception e) {
//Log.e("Error", e.getMessage());
e.printStackTrace();
}
I use
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MobnoAct.this, android.R.layout.simple_spinner_item, Countrylist);
mySpinner.setAdapter(adapter);
mySpinner.setSelection(0);
But in the spinner Its showing a default country name..But I want The country name will be as per locale..
like :--
Locale defaultLocale = getResources().getConfiguration().locale;
String si=defaultLocale.getCountry();
How I can do that???
Try this after you set the adapter and retrieve the default local:
for(String countryName : countryList)
for(CountryInfo country : countryinfo)
if(country.getName().equals(countryName) && country.getCode().toLowerCase().equals(si.toLowerCase()))
mySpinner.setSelection(adapter.getPosition(countryName));
Hope this helps
Related
Why i am getting only last value of an array. My array "arr" contains list of values but when i use it in spinner i am getting only last value of an array. Thanks in advance!!!
public void addItemsOnSpinner2(String[] arr) {
List list = new ArrayList(Arrays.asList(arr));
//System.out.println("Function Currency value===>"+list);
System.out.println("Function Currency value===>"+Arrays.toString(arr));
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
List<Currency> dataList = currencyExchange.getCurrencyList();
Iterator<Currency> iterator = dataList.iterator();
while (iterator.hasNext()) {
try {
//System.out.println("hhhhhhhhhhh=>" + iterator.next().getName());
currencyName= iterator.next().getName();
//String[] words=currencyName.split(" ");
arr=currencyName.split(" ");
System.out.println("Currencyname==>"+ Arrays.toString(arr));
}
catch (NoSuchElementException e){
System.out.println("Continue");
}
addItemsOnSpinner2(arr);
}
The reason you are only getting last value because in while loop you are using
one variable, so when you update new value of iterator into it, it is
replaced by old value
Convert your iterator to ArrayList like this :
Iterator<Currency> iterator = dataList.iterator();
List<String> arList= Lists.newArrayList(iterator);
Then call your method addItemsOnSpinner2(String[] arr) like this :
addItemsOnSpinner2(arList);
Edit:
Replace
while (iterator.hasNext()) {
try {
//System.out.println("hhhhhhhhhhh=>" + iterator.next().getName());
currencyName= iterator.next().getName();
//String[] words=currencyName.split(" ");
arr=currencyName.split(" ");
System.out.println("Currencyname==>"+ Arrays.toString(arr));
}
catch (NoSuchElementException e){
System.out.println("Continue");
}
addItemsOnSpinner2(arr);
with
String[] arr = dataList.toArray();
addItemsOnSpinner2(arr);
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);
I need to extract part of the string and display it in the spinner
I need that when the spinner display data example
For array entries like the following
"Equipo-001"
"Equipo-002"
Should show only:
"001"
"002"
Here's my code
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina());
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
ArrayList<String> numberFolios = new ArrayList<>();
for(int j =0; j < folios.size(); j++){
numberFolios.add(folios.get(j).substring(8, 10));
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, numberFolios);
Check link for better reference on how to use substring.
You can use SPLIT function
ArrayList<String> data = new ArrayList();
foreach(String get:folios){
data.add(folios.split("-")[1]);
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If your result will be dynamic(The string length would vary in future) the below solution may work,
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
try{
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina().toString().split("-")[1]);
}
} catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
I'm using two Spinners to show the items I'm getting from the json response. I have 2 problems right now. When u check my logcat u can see there are items repeating (Right side list, u can see so many pan). I want to have 1 item only once in my Spinner. I want to use something similar to distinct we use in sql databases.
My second problem is,
Select pan in the 1 spinner then 2nd spinner should contain items related to pan. (select pan in 1st spinner and 2nd should display only Pan large, pan medium and personal pan)
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
JSONArray extraItemEntityArray = subMenuObject
.getJSONArray("ExtraItemEntity");
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output of this
Call this method to get distinct descriptions and then set the adapter using the return value of this function...
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
For instance
description = Utils.removeDuplicatesFromList(description);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
NOTE:
I would suggest you make a new class call it Utils.java and place the above method inside it and then call it i have mentioned above.
Like this...
import java.util.ArrayList;
public class Utils
{
private Utils()
{
//Its constructor should not exist.Hence this.
}
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
}
I hope it helps.
i have a lazy list that loads in a list of images at the moment the urls are hard coded in a String[] and i'm wanting to load them via a json feed. so my question is how can i create a string[] from a JsonObject?
heres what ive got so far
try {
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
fulldata = String.valueOf(json);
Log.v("myApp","newsdata" + fulldata);
newsList = new ArrayList<String>();
newsList2 = new ArrayList<String>();
newsList3 = new ArrayList<String>();
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
for(int t = 0; t < newsAmount; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
//this is where i want to load the images into a String[]
JSONArray ImageArray = objData.getJSONArray("news");
newsList3.add(newsTitleDict.getString("title"));
}
for(int t = 0; t < 1; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
newsList.add(newsTitleDict.getString("title"));
newsList2.add(newsTitleDict.getString("title"));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
//arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);
String[] mStrings={
"http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png",
"http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png",
"http://a3.twimg.com/profile_images/121630227/Droid_normal.jpg",
"http://a1.twimg.com/profile_images/957149154/twitterhalf_normal.jpg",
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
};
arrayAdapter3 = new LazyAdapter(this, mStrings);
ListView list = getListView();
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header = inflater.inflate( R.layout.homeheader, list, false);
View header2 = inflater.inflate( R.layout.homeheader2, list, false);
View header3 = inflater.inflate( R.layout.homeheader3, list, false);
adapter = new MergeAdapter();
adapter.addView(header);
adapter.addAdapter(arrayAdapter);
adapter.addView(header2);
adapter.addAdapter(arrayAdapter2);
adapter.addView(header3);
adapter.addAdapter(arrayAdapter3);
setListAdapter(adapter);
}
This is how I add values to a String[] using an ArrayList from a JSONObject. My example uses a JSONArray, but you can always change that to fit your code.
ArrayList<String> arrayName = new ArrayList<String>();
ArrayList<String> arrayPicture = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
try {
JSONArray JAFriends = new JSONArray(apiResponse);
for (int i = 0; i < JAFriends.length(); i++) {
json_data = JAFriends.getJSONObject(i);
if (json_data.has("name")) {
String getFriendName = json_data.getString("name").toUpperCase();
arrayName.add(getFriendName);
} else {
String getFriendName = null;
arrayName.add(getFriendName);
}
if (json_data.has("pic_square")) {
String getFriendPhoto = json_data.getString("pic_square");
arrayPicture.add(getFriendPhoto);
} else {
String getFriendPhoto = null;
arrayPicture.add(getFriendPhoto);
}
}
} catch (JSONException e) {
return;
}
stringName = new String[arrayName.size()];
stringName = arrayName.toArray(stringName);
stringPicture = new String[arrayPicture.size()];
stringPicture = arrayPicture.toArray(stringPicture);
listofFriends = (ListView)findViewById(R.id.list);
adapter = new FriendsAdapter(this, stringName, stringPicture);
listofFriends.setAdapter(adapter);
In he for loop, using if statements to ensure no errors creep in, the returned values are added to their respective ArrayLists and 6 lines of code before the adapter is set, the values from the ArrayLists are added to the String[].
Hope this helps solve your question.