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);
Related
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.
Im trying to getAll strings from a SharedPreferences file with particular keys.
Here is my code
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String,?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getValue() instanceof String) {
if (entry.getKey() == currentList + "ItemName") {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, checkListStrings );
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
The line:
if (entry.getKey() == currentList + "ItemName") {
is causing the problem. The result of this is an empty ListView. Ideas?
Here is how the strings are saved to the shared preferences:
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename,0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(checkListStringData + "ItemName", checkListStringData);
checkListEditor.commit();
and currentList is a string whos value is determined by an item clicked in a different listview.
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
I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).
I am using setListAdapter for displaying the users online..
Here's my code:
Vector<String> myvector= Receiver.user;
int i =0;
String[] strings =new String[myvector.size()];
for(String str : myvector) {
strings[i] = str;
i++;
}
setListAdapter(new ArrayAdapter<String>(Display.this, android.R.layout.simple_list_item_1, strings));
The vector gets updated every time a new user comes online.But the display is not changing.
How to update it??
Thanks in advance
use the notifyDataSetChanged() of ArrayAdapter
Check here
Create your code as a method
for example
make it as
public void yourMethod()
{
Vector<String> myvector= Receiver.user;
int i =0;
String[] strings =new String[myvector.size()];
for(String str : myvector) {
strings[i] = str;
i++;
}
setListAdapter(new ArrayAdapter<String>(Display.this, android.R.layout.simple_list_item_1, strings));
}
call this Method.
When a user is created newly
so that it works