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
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;
}
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);
I'm new at android. I trying to get the data from Database and put it into HashMap. But I got a little problem here. I got an error when I try to put the data that I get.
I put a comment on the error line in my code. You can check it below
Here's my class
private static final String TAG_ITEM_NAME = "item_name";
// Hashmap for ListView
ArrayList<HashMap<String, String>> searchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchlist = new ArrayList<HashMap<String, String>>();
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult(searchResult);
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
//AllItem item_name = all_Items.put(cn.getItem_name(), cn);
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
}
searchlist.add(all_Items);
ListAdapter adapter = new SimpleAdapter(
Search.this, searchlist,
R.layout.searchlayout, new String[] {TAG_ITEM_NAME},
new int[] { R.id.category_name}
);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
The error said The Method put(String, Allitem) int type Hashmap<String,Allitem> is not applicable for the argument (String, String)
How to fix this error? Thanks before :D
all_items takes a String and an AllItem, but you are placing two Strings into it in this line:
// TAG_ITEM_NAME is a String and item_name is also a String
all_Items.put(TAG_ITEM_NAME,item_name);
You try to put in the map as a value string but you map expect as a value AllItem, so you must modify your code in this way:
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
all_Items.put(item_name , cn );
}
This code will add your class object to the map with the key which equals to your object name.
all_Items is defined as a hashmap to contain <String, AllItem> key value pairs as defined here:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
but you are trying to push <String,String> key value pair into your all_Items hashmap :
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
It seems you want to push the AllItem object against its item_name, which can be done as:
all_Items.put(item_name, cn);
Your HashMap is as follows:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
This means it has String keys and AllItem values. You can put a AllItem object inside this HashMap.
When you write
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
you are putting a String inside the HashMap hence it is giving error.
You should be doing:
all_Items.put(TAG_ITEM_NAME,cn);
Your hashmap is <String, Allitem>. While you try to put <String, String> in it.
all_Items.put(TAG_ITEM_NAME, item_name);
should be changed to
all_Items.put(TAG_ITEM_NAME, cn);
Hope you got the difference.
I dont see connection in the code but using the given information, your error probably is related to your searchlist variable in your code.
change this:
ArrayList<HashMap<String, String>> searchlist;
to this:
ArrayList<HashMap<String, AllItem>> searchlist;
it's because you declared HashMap<String, AllItem> and you try to putall_Items.put(TAG_ITEM_NAME,item_name); which would probably be HashMap<String, String>().
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)?