Android Items not added to listview - android

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.

Related

Listview not updating based on value on Array Adapter

I call the method below to update my listview
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
ListAdapter adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
but that code is associated with a value that changes and also this is the other code
private ArrayList<plan_model> getItems_search(String param_cusname) {
Cursor data = myDb.get_search_plan(pattern_email, param_name);
int i = 0;
while (data.moveToNext()) {
String date = data.getString(3);
String remarks = data.getString(4);
items.add(new plan_model(cusname, remarks);
}
return items;
}
and this is my sorter
private ArrayList sortAndAddSections(ArrayList<plan_model> itemList) {
Collections.sort(itemList);
plan_model sectionCell;
tempList.clear();
tmpHeaderPositions.clear();
String header = "";
int addedRow = 0;
int bgColor = R.color.alt_gray;
for (int i = 0; i < itemList.size(); i++) {
String remarks = itemList.get(i).getRemarks();
String date = itemList.get(i).getDate();
if (!(header.equals(itemList.get(i).getDate()))) {
sectionCell = new plan_model(remarks, date);
sectionCell.setToSectionHeader();
tmpHeaderPositions.add(i + addedRow);
addedRow++;
tempList.add(sectionCell);
header = itemList.get(i).getDate();
bgColor = R.color.alt_gray;
}
sectionCell = itemList.get(i);
sectionCell.setBgColor(bgColor);
tempList.add(sectionCell);
if (bgColor == R.color.alt_gray) bgColor = R.color.alt_white;
else bgColor = R.color.alt_gray;
}
tmpHeaderPositions.add(tempList.size());
for (int i = 0; i < tmpHeaderPositions.size() - 1; i++) {
sectionCell = tempList.get(tmpHeaderPositions.get(i));
sectionCell.setDate(sectionCell.getDate() + " (" +
(tmpHeaderPositions.get(i + 1) - tmpHeaderPositions.get(i) - 1) + ")");
}
return tempList;
}
my question is the value name changes but my listview is not how can I update my listview? because i need to update it based on search parameter
If your itemList is being updated properly, you don't need to create another instance of the adapter, just use notifyDataSetChanged():
private void createList() {
ListView list = (ListView) listView.findViewById(R.id.plan_list);
itemsList = sortAndAddSections(getItems_search(name));
adapter = new ListAdapter(getActivity(), itemsList);
list.setAdapter(adapter);
}
private void updateList() {
sortAndAddSections(getItems_search(name)); // Update itemList without re-assign its value, otherwise the adapter will loose reference
adapter.notifyDataSetChanged()
}
In getItems_search() add this line at the beginning:
items.clear();
Every time the value of name changes you have to do the following:
itemsList.clear();
itemsList = sortAndAddSections(getItems_search(name));
list.setAdapter(new ListAdapter(getActivity(), itemsList));

Why i am getting last value of an array in spinner?

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);

How to get Hashmap Data

I had seen many examples regarding Hashmap Data but I am not getting the data as required.
Here is my code:
HashMap<String,ArrayList<String>> citylist = new HashMap<String, ArrayList<String>>();
ArrayList<String> Gujarat = new ArrayList<String>();
Gujarat.add("Surat");
Gujarat.add("Baroda");
Gujarat.add("Ahmedabad");
ArrayList<String> Rajasthan = new ArrayList<String>();
Rajasthan.add("Udaipur");
Rajasthan.add("Jaipur");
ArrayList<String> UP= new ArrayList<String>();
UP.add("Lucknow");
UP.add("Agra");
citylist.put("Gujarat", Gujarat);
citylist.put("UP", UP);
citylist.put("Rajasthan", Rajasthan);
It is in recyclerview how to get this type of data in BindViewHolder?
Toast is coming like:
{Rajasthan=[Udaipur, Jaipur], UP=[Lucknow, Agra], Gujarat=[Surat, Baroda, Ahmedabad]}
I had used this method to get but error is coming:
public void onBindViewHolder(MyViewHolder holder, int position) {
ArrayList<String> lst = citylist.get("" + position);
for (Integer i = 0; i < lst.size(); i++) {
holder.tv.setText(citylist.toString());
Log.e("Hashmap....", ""+holder.tv );
}
the output should be like Gujarat is state and surat baroda and ahmedabad are cities?
First create one ArrayList with all state :
ArrayList<String> stateList = new ArrayList<String>();
stateList.add("Gujarat");
stateList.add("UP");
stateList.add("Rajasthan");
Second create one HashMap with each state name as Key and each state city as Value:
HashMap<String,ArrayList<String>> stateCityMap = new HashMap<String,ArrayList<String>>()
ArrayList<String> gujaratCityList = new ArrayList<String>();
gujaratCityList.add("Ahmedabad");
gujaratCityList.add("Surat");
gujaratCityList.add("Baroda");
.......................
ArrayList<String> upCityList = new ArrayList<String>();
upCityList.add("Lucknow");
upCityList.add("Agra");
..........................
ArrayList<String> rajasthanCityList = new ArrayList<String>();
rajasthanCityList.add("Udaipur");
rajasthanCityList.add("Jaipur");
...........................
stateCityMap.put("Gujarat",gujaratCityList);
stateCityMap.put("UP",upCityList);
stateCityMap.put("Rajasthan",rajasthanCityList);
Now get all city name based on state in Adapter :
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.e("State : ",stateList.get(position));
ArrayList<String> cityList= (ArrayList<String>)stateCityMap.get(stateList.get(position));
for(String cityName : cityList){
Log.e("City : ",cityName);
}
}
you can get like below.
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key=(String)iterator.next();
String value=(String)map.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
HashMaps do not preserve ordering:
This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant
over time.
Take a look at LinkedHashMap, which guarantees a predictable iteration order.
You might wanna try something like this.
for (Map.Entry<String, ArrayList<String>> entry : citylist.entrySet())
{
String key = entry.getKey(); // Your State
String value = entry.getValue(); // Your List of Cities.
// Split data and insert in Views
}
However I recommend (for easy to use case) keep a List of all the states and get Value from HashMap using keys from this List of states.
Please check it :
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> h1 = new HashMap<String, String>();
h1.put("h1_key_1", "h1_value_1");
h1.put("h1_key_2", "h1_value_2");
arrayList.add(h1);
for (HashMap<String, String> hashMap : arrayList) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
Try This:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}

Listview of backendless directories

I'm using backendless and I'm trying to display my directories in a listview. I'm using Android Studio.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION);
Backendless.Files.listing("/Uploads", "*docs", true, new AsyncCallback<BackendlessCollection<FileInfo>>() {
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
String[] info = {URL, publicURL, name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, info);
getListView().setAdapter(adapter);
}
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
}
}
It has no error but the app doesn't open. Can anyone help me what to do?
Here is the start for fixing your problem:
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
// create a list for your data
List<String> infoList = new ArrayList<>();
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
// put everything into one string temporarily
// String[] info = {URL, publicURL, name};
String info = URL + " " + publicURL + " " + name;
infoList.add(info);
}
// loop through ALL your data before creating/assigning adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, infoList);
getListView().setAdapter(adapter);
}
Now your adapter is going to get a little more complicated, because you will not want to have everything on one line. You will need to create a layout for your list item. Then you need to use either SimpleAdapter or create a custom class extending BaseAdapter and use that to display your data.

checkbox + customAdapter + listview + sharedpreferences

I have a listview with a custom adapter of two lines(textview) and one checkbox.
I would like to save the state of the checkbox when I close the app, but I don't know how, I tried many things but nothing!
I can do it with a android.R.layout.simple_list_item_multiple_choice but no with my adapter.
onCreate
private SimpleAdapter notes;
ArrayList<HashMap<String, String>> arraylist_hashmap = new ArrayList<HashMap<String, String>>();
if (lenguage.equals("Deutsch")) {
HashMap<String, String> item;
for (int i = 0; i < StatesAndCapitalsAleman.length; i++) {
item = new HashMap<String, String>();
item.put("line1", StatesAndCapitalsAleman[i][0]);
item.put("line2", StatesAndCapitalsAleman[i][1]);
arraylist_hashmap.add(item);
}
notes = new SimpleAdapter(this, arraylist_hashmap, R.layout.main_item_two_line_row,
new String[] { "line1", "line2" },
new int[] { R.id.text1, R.id.text2 });
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
setListAdapter(notes);
Save state
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
SaveSelections();
super.onBackPressed();
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the
// user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.listView_ale.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.listView_ale.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.listView_ale.getItemAtPosition(i);
} else {
savedItems += this.listView_ale.getItemAtPosition(i);
}
}
}
return savedItems;
}
You need to create an create an custom adapter with your own model with.
Create model which has a selected boolean field an other fields as per your requirement. And then create a custom adapter for your list. and then you can modify the model object on the checkbox's check state as selected true/false and latter you can save the sate as per your requirement.

Categories

Resources