I am having a difficulty upon converting arraylist to hashSet. I dont have knowledge about HashSet that why I use ArrayList. I've read some about it but understand none. I am here trying to get some help about my problem.
All I wanted is to NOT DUPLICATE the words entered in my app's ListView. Here's my code. Please bear with it. I've seen some questions too here but it got me a lot more confused. Please be nice.
P.S. My first try :)
ArrayAdapter<String> adapter;
//onCreate
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
wordList.setAdapter(adapter);
//SEARCH
public void viewWord(View view) {
s1 = search.getText().toString();
s2 = dbHelper.getData(s1);
if (optionTxtView == 0) {
tv2.setText(s2);
optionTxtView = 1;
} else {
if (optionTxtView == 1) {
tv3.setText(s2);
optionTxtView = 1;
}
}
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
ListView works by returning data based on position. Sets do not have a notion of position; you have to iterate over the Set to find the element you want.
On the other hand, Lists do have a notion of position, this is why they play nicely with ListView and the BaseAdapter class.
Adding ArrayList elements to a HashSet (Note: use LinkedHashSet if the order of elements matters):
ArrayList<String> list = new ArrayList<String>();
HashSet<String> set = new HashSet<String>();
list.add("Hello");
list.add("Hello");
list.add("World!");
System.out.println(list); // [Hello, Hello, World!]
set.addAll(list);
System.out.println(set); // [Hello, World!]
Using your code, maybe you could try something like:
ArrayAdapter<String> adapter;
//onCreate
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
HashSet<String> noDupesSet = new HashSet<String>();
noDupesSet.addAll(wordlist);
wordlist.clear();
wordlist.addAll(noDupesSet);
wordList.setAdapter(adapter);
//SEARCH
public void viewWord(View view) {
s1 = search.getText().toString();
s2 = dbHelper.getData(s1);
if (optionTxtView == 0) {
tv2.setText(s2);
optionTxtView = 1;
} else {
if (optionTxtView == 1) {
tv3.setText(s2);
optionTxtView = 1;
}
}
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
Related
I am trying to fill the listview on a SET button.As i select the values spinner and according to list will fill. Problem i am facing is at many times i click on SET button it will add items to listview .
setButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
for (int i = 0; i < DeviceID.size(); i++)
{
//initialize row data
for (int j = 0; j < 5; j++) {
if (j == 0)
str = DATE.get(i);
else if (j == 1)
str = TIME.get(i);
else if (j == 2)
str = DeviceID.get(i);
else if (j == 3)
str = SMSTEXT.get(i);
map.put(columnTags[j], str);
}
mylistData.add(map);
}
final String[] columnTags = new String[]{"one", "two", "three", "four", "five", "six", "lat", "log"};
final int[] columnIds = new int[]{R.id.textView5, R.id.textView8, R.id.textView9,R.id.checkbox, R.id.textView10};
arrayAdapter = new SimpleAdapter(this, mylistData, R.layout.location_locator_textview, columnTags, columnIds);
listview.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
});
It looks like your list mylistData is a global variable. So, the old items are still in the list.
Either make it local inside the onClick method, or clear it in the first line of the onClick method. (Also the same case for map)
public void onClick(View view){
mylistData.clear();
map.clear();
//your code
}
You can call listview.setAdapter(null); before you set your items into listview
Try to modify the list of an element in your adapter and then call notifyDataSetChanged().
It would be easier if you post the code
Hi guys I'm having difficulty figuring out why my buttons wont display the right text and display junk code. I am running a serverRequest then creating the buttons after the details are gotten and I surely did test I am getting the right string back from the server.
public void getCourses(User user) {
ServerRequest serverRequest = new ServerRequest(this);
serverRequest.fetchUserCoursesDataInBackground(user, new getUserCallback() {
#Override
public void doneString(String[] returnedString) {
if (returnedString == null) {
System.out.println("DONE EMPTY");
} else {
userLocalStore.storeUserCourses(returnedString);
final ListView listView = (ListView) findViewById(R.id.viewCourseList);
final ArrayList<Button> list = new ArrayList<>();
View v = getWindow().getDecorView();
for (int i = 0; i < returnedString.length; i++) {
System.out.println("This is in for loop:" +returnedString[i]);
Button button = new Button(v.getContext());
button.setText(returnedString[i]);
button.setId(i);
button.setHeight(40);
button.setWidth(100);
list.add(button);
}
if (list.isEmpty()) {
System.out.println("List is empty bro");
} else {
final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
System.out.println("Adding adapter");
}
}
}
this is the whole code. I will show you what it is displaying on the application
this is the bug
I see 3 problems in this code:
1st i assume java can mess this 1 up:
replace> final ArrayList list = new ArrayList<>();
with> final ArrayList list = new ArrayList();
2nd you are using a layout "android.R.layout.simple_list_item_1" for the ArrayAdapter which is an xml layout including a text view thus you screenshot shows 2 text views and not buttons.
3rd new ArrayAdapter() constructor takes a list of Strings. so if you...
replace> final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, list);
with> final ArrayAdapter adapter = new ArrayAdapter(v.getContext(), android.R.layout.simple_list_item_1, returnedString);
you will see buttons with the text that you are printing in your loop.
I need some help guys.
The problem is that I have a spinner that has commodities in it, such as chemicals,biscuits etc. but these commodities are stored in the database. I have written a web service that retrieves the commodities and the corresponding commodity code from database the web service works fine. I am getting the data in my android code. So I have stored the commodity in one array list say ar1, and the commodity code in one more array list say ar2. Now I want these commodity, what I have stored in ar1 to be displayed as spinner items and when user selects one of the spinner items, I must be able to retrieve the corresponding commodity code of that commodity.
Can some body help me??
I am using the below code but i am not able to get the desired result
String[] arr_Commodities = new String[ar2.size()];
spinnerMap = new HashMap<String, String>();
for (int i = 0; i < ar2.size(); i++)
{
spinnerMap.put(ar2.get(i),ar1.get(i));
arr_Commodities[i] = ar2.get(i);
System.out.println(arr_Commodities[i]);
}
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
adapter =new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, arr_Commodities);
spin_commodity.setAdapter(adapter);
I find nothing is wrong with this code but i am still not able to pop[ulate the spinner some one please modify the above code..thank you
you can try this and improvise the loop on populating items:
final ArrayList<String[]> items = new ArrayList<String[]>();
for(int i= 0; i <10 ; i++){//sample loop populating items
String[] item = new String[2];
item[0] = "id";
item[1] = "commodities";
items.add(item);
}
Spinner s = new Spinner(context);//sample spinner
ArrayAdapter<String[]> adapter = new ArrayAdapter<String[]>(context , android.R.layout.simple_list_item_1, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
String[] selected = items.get(position);
//commodity id
String comId = selected[0];
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
String[] ar1={"chemicals","biscuits"};
String[] ar2={"1","2"};
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar1); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
your_spinner.setAdapter(adapter);
//to get the selected item position
int x=your_spinner.getSelectedItemPosition();
Your required code is
String code=ar2[x];
In my app, I want the users to see a list of cities, select the city, then see people associate with that city.
So, I have this to get the data:
protected void onResume() {
super.onResume();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.orderByAscending(ParseConstants.KEY_LOCATION);
query.setLimit(1000);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> users, ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success
mMidwifeLocation = users;
String[] locations = new String[mMidwifeLocation.size()];
String check;
int i = 0;
for(ParseUser user : mMidwifeLocation) {
check=user.getString("city");
if(check!=null){
if(!Arrays.asList(locations).contains(check)){
locations[i] = user.getString("city");
}
}
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
setListAdapter(adapter);
}
else {
Log.e(TAG, e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(SearchingMidwife.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
And this to pass the selected item to the new activity:
#Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id);
SparseBooleanArray checked = l.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
selectedItems.add(adapter.getItem(position));
}
String[] outputStrArr = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i);
}
Intent intent = new Intent(getApplicationContext(),
MidwifeResultList.class);
// Create a bundle object
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
// start the ResultActivity
startActivity(intent);
}
When I try it though, the app stops with an error once I select the item...
FATAL EXCEPTION: main Process: android.bignerdranch.com.mobilemidwife,
PID: 31604 java.lang.NullPointerException at
android.bignerdranch.com.mobilemidwife.SearchingMidwife.onListItemClick(SearchingMidwife.java:169)
Which points to this:
if (checked.valueAt(i)) selectedItems.add(adapter.getItem(position)); }
I declare adapter before onCreate:
ArrayAdapter adapter;
I assume this is the same adapter that is used in OnResume...something is not quite right, not sure what that would be. It seems like the adapter from onResume is not being passed into onResume, as it is null.
I am a bit new to this, so trying to learn this as best I can; I apologize if the problem is something missed that is simple.
Thanks so much for your help/insights
Michael Cabus
Your problem is here:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
This is creating a local variable which is only scoped inside the method.
Change it to
adapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
by removing the leading ArrayAdapter<String> and that should fix this particular problem.
Update:
May I suggest using a different coding style such as putting leading underscore to your class member variables so that it's easier to detect these problems in the future? it's only a suggestion but I've found it immensely helpful to adapt this particular style.
What I mean is to for instance declare your variable like
ArrayAdapter _adapter;
in your class and then set it like this:
_adapter = new ArrayAdapter<String>(
SearchingMidwife.this,
android.R.layout.simple_list_item_checked,
locations);
Now every time you see "_", it's indicating that it's a member variable and not a local variable (since you would declare those without the leading underscore).
Just a personal suggestion. Up to you to adopt it or leave it.
I wanted to make a listview with alphabetical adapter so that you can see the letters mapped to each section when fastscrolling. The following works correctly when the listview is initialised. However, if the list changes (e.g. adding or removing rows) the indexer does not seem to update even though a new adapter is created each time. It uses the same set of alphabets as the original list.
private void GenerateListView (final ArrayList<String> listItems) {
try {
listView = (ListView) findViewById(R.id.listView_browser);
// generate section index adapter
AlphabeticalAdapter adapter = new AlphabeticalAdapter(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
// recall scroll position
if (_currPos < listItems.size())
listView.setVerticalScrollbarPosition(_currPos);
} catch (Exception e) {
e.printStackTrace();
}
}
The following is the alphabetical adapter class.
public class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer
{
private HashMap<String, Integer> alphaIndexer;
private String[] sections;
public AlphabeticalAdapter(Context c, int resource, List<String> data)
{
// create ArrayAdapter<String>
super(c, resource, data);
// generate HashMap
alphaIndexer = new HashMap<>();
// generate index
for (int i = 0; i < data.size(); i++)
{
// convert first letter of each entry to upper case
String s = data.get(i).substring(0, 1).toUpperCase();
// map letter with corresponding index
if (!alphaIndexer.containsKey(s))
alphaIndexer.put(s, i);
}
// assign set view of keys in the HashMap
Set<String> sectionLetters = alphaIndexer.keySet();
// generate list from the set view
ArrayList<String> sectionList = new ArrayList<>(sectionLetters);
// sort list alphabetically
Collections.sort(sectionList);
// define and populate string array with the letters
sections = new String[sectionList.size()];
for (int i = 0; i < sectionList.size(); i++)
sections[i] = sectionList.get(i);
}
See this solution Code.
And to update SectionIndexer using filter or any data change override this method. It's work for me.
#Override
public void notifyDataSetInvalidated() {
//write your code
super.notifyDataSetInvalidated();
}