Consider the following combo list
comboList = new Spinner(this);
list_arr = new ArrayList<String>();
The ArrayList is filled with Strings from SharedPreferences and the Spinner is populated in this way
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list_arr);
comboList.setAdapter(dataAdapter);
Then it gets updated in case of an event OnClickListener()
list_arr.clear();
ArrayList<String> res = getMyLists();
for (int i = 0; i < res.size(); i++) {
list_arr.add(res.get(i));
}
How can I refresh also the already selected item programmatically?
From the GUI, I have to manually select another value from the list and then change it back.
This could be a duplicate of this other question but it is very old and unanswered.
You may have to call dataAdapter.notifyDataSetChanged();
In this case, you'll need to re-create the spinner's adapter:
list_arr.clear();
ArrayList<String> res = getMyLists();
for (int i = 0; i < res.size(); i++) {
list_arr.add(res.get(i));
}
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_arr);
comboList.setAdapter(dataAdapter);
Related
I am attempting to create a ListView to display values entered via an EditText. I am using an ArrayList and ArrayAdapter but I am afraid I don't fully understand how they work.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
I am unsure why I am unable to use android.R.id.listView1 where listView1 is the id of my list view in the activity. Is this not the resourceid that the adapter needs to list off my ArrayList?
Below is my full method and delcarations. Sorry if I am being vague in my questions, I don't fully know which terminology to use for what and I don't intend to cause confusion.
public ArrayAdapter<String> adapter;
ArrayList<String> allScores = new ArrayList<>();
ListView listScores = (ListView)findViewById(R.id.listView1);
public void onButtonClick(View V){
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
TextView output2 = (TextView) findViewById(R.id.custName); //TEST FOR ARRAY LIST DISPLAY
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
} else {
//savedScores.add(input1.getText().toString());//Save input into array list
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
output1.setText("Your score is : " + Integer.toString(sum));
input1.setText(""); //Clear input text box
}
};
For some background information on my intentions, I want the user to enter integers in an EditText, save these values in an ArrayList, and then populate a ListView line-by-line with the values the user entered. Thank you for the help.
Try This way.
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);
here you have to use setadapter of listview not put in the adapter
try this
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,allscores);
listscores.setAdapter(adapter)
if you want to add input things than make an Arraylist and simply pass it in adapter's third parameter
UPDATE: PROBLEM FIXED -
The ActionBar was covering the first item on the list.
SOLUTION: Android AppBarLayout overlaps listview
In my program, I am retrieving data from the database and displaying it using List View.
However, the first row elements are always skipped in the process and the display begins from the second row.
public void displaydata(){
Cursor res = myDb.getAllData();
lv = (ListView) findViewById(R.id.idListView);
if(res.getCount() == 0){
//show message
return;
}
ArrayList<String> buffer = new ArrayList<>();
while(res.moveToNext()){
buffer.add(res.getString(1));
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer);
lv.setAdapter(adapter);
}
How do I make it display from the first row?
Any help is appreciated, thanks.
EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
Try changing
while(res.moveToNext()){
buffer.add(res.getString(1));
};
to
Edit: change the while so it increments after:
do {
buffer.add(res.getString(1));
} while (cursor.moveToNext());
Personally, I would recommend a CursorAdapter when using a database.
lv = (ListView) findViewById(R.id.idListView);
String from = { COLUMN_NAME };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
myDb.getAllData(),
from, to);
lv.setAdapter(adapter);
Try out this this code may be useful for fetching data from db using cursor.
public ArrayList<BasicInfo> getFetchBasicInfo() {
ArrayList<BasicInfo> data = new ArrayList<BasicInfo>();
String sql = "select * from basic_info;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
String LastName = c.getString(c.getColumnIndex("last_name"));
String Sabcription = c.getString(c
.getColumnIndex("salutation_id"));
data.add(new BasicInfo(FirstName, LastName));
}
c.close();
}
return data;
}
I have 2 sets of values in my app - 1 from resources file and 1 from sharedpreferences. Is there an easy way to combine these both and create a Sorted List for the adapter? Here is my code:
Spinner copyFromCity = (Spinner) findViewById(R.id.spinner);
Resources res = getResources();
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
// Necessary to add Iterator String to an adapter
ArrayList<String> sortedPredefinedCities = new ArrayList<String>();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
new ArrayList(Arrays.asList(predefinedCities)));
// Add values from our custom cities onto the Adapter via SharedPreferences
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
while(userCities.hasNext()){
adapter.add(userCities.next());
}
/* TODO Way to sort both these values into alphabetical order */
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
copyFromCity.setAdapter(adapter);
Adding readCitiesFromPref() method for clarifying why Iterator is being returned
protected Iterator<String> readCitiesFromPref() {
// See if preferences store this
JSONObject citiesList = null;
Iterator<String> userCities = null;
try {
// Yes, so get the values out
citiesList = new JSONObject(prefs.getAll());
userCities = citiesList.keys();
} catch (NullPointerException e1) {
//TODO
}
return userCities;
}
What I think is add those arrays/list to a List, sort and set it to adapter
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
List<String> copyOfCities = new ArrayList<String>();
while (userCities.hasNext()){
copyOfCities.add(userCities.next());
}
ArrayList<String> sortedCities = new ArrayList<String>();
sortedCities.addAll(copyOfCities);
sortedCities.addAll(Arrays.asList(predefinedCities));
Collections.sort(sortedCities);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
sortedCities);
You can do like this:
Convert the string array to a List
convert the Iterator to List
Combine them
Sortthem like Collections.sort(yourCombinedList);
feed them to the adapter
I have my two arraylist and I have merged their data like this
ArrayList prayerNames={Fajar,Zohar,Asar,Magrib,Isha};
ArrayList prayerTime={4:04am,2:58pm,4:20pm,5:09pm,8:10pm}
ArrayList<String> mergedList= new ArrayList<String>();
for(int i=0;i<prayersTime.size();i++){
mergedList.add(prayerNames.get(i)+""+prayerTimes.get(i));
}
fajarText.append(mergedList.get(0));
zoharText.append(mergedList.get(2));
asarText.append(mergedList.get(4))
But now when I want to get data from merged list with specific index my activity got stops.
Need Help
Your ArrayList initialization is not correct. Try this:
ArrayList<String> prayerNames = new ArrayList<String>();
prayerNames.add("Fajar");
prayerNames.add("Zohar");
prayerNames.add("Asar");
prayerNames.add("Magrib");
prayerNames.add("Isha");
ArrayList<String> prayerTimes = new ArrayList<String>();
prayerTimes.add("4:04am");
prayerTimes.add("2:58pm");
prayerTimes.add("4:20pm");
prayerTimes.add("5:09pm");
prayerTimes.add("8:10pm");
ArrayList<String> mergedList = new ArrayList<String>();
for (int i = 0; i < prayerTimes.size(); i++) {
mergedList.add(prayerNames.get(i) + "" + prayerTimes.get(i));
}
fajarText.append(mergedList.get(0));
zoharText.append(mergedList.get(2));
asarText.append(mergedList.get(4));
i'm trying to retrieve data from a hashmap with multiple values for 1 key and set it to a listview,but instead of setting the values
into the listview and displaying the listview,all that is displayed is the array(without the key).
The code is as follows:
ListView lv = (ListView)findViewById(R.id.list);
//hashmap of type `HashMap<String, List<String>>`
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
for (int i = 0; i < j; i++) {
values.add(value1);
values.add(value2);
hm.put(key, values);
}
and to retrieve the values and put in a listview
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, Arrays.asList(hm),
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
an example is where the key=1,value2=2 and value3=3,it will display the an array that looks like [2,3].
how do i get it to display the lisview and add the key too?
SimpleAdapters Consturctor states as it's second parameter:
data: A List of Maps. Each entry in the List corresponds to one row in
the list. The Maps contain the data for each row, and should include
all the entries specified in "from"
but HashMap<String, List<String>> hm is a map of lists. So like List<Map<String,String>> hm would be the datatype you probably need.
Here is the edited source:
ListView lv = (ListView)findViewById(R.id.list);
List<Map<String,String>> mapList = new ArrayList<Map<String, String>>();
Map<String,String> mapPerRow;
for (int i = 0; i < rowNumbers; i++) {
mapPerRow = new HashMap<String, String>();
mapPerRow.put("column1", value1);
mapPerRow.put("column2", value2);
mapList.add(mapPerRow);
}
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, mapList,
R.layout.list_item, new String[] { "column1", "colum2"},
new int[] { R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
I don't get why you want the key in it (just add Strings to the map if you need more)?