I use these 2 methods for save and load my array list and I need to save my array list after each item dynamically added to array.
public void addItems(int howMany){
if (howMany > 0) {
int lastInsertedIndex = 11;
for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
mList.add("Item " + i);
notifyItemInserted(mList.size() - 1);
}
lastInsertedIndex = lastInsertedIndex + howMany;
}
}
and my save and load method:
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(mainListAdapter.mList);
editor.putStringSet("list", set);
return editor.commit();
}
public ArrayList<String> getArray() {
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}
My problem is : when I add a new item with button nothing happen and like the array list is full how to fix this ?
The the following:
Declare myList globally:
ArrayList<String> myList = new ArrayList<String>();
For setting value:
for (int i = 0; i < totalSize; i++) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("number" + i, value + "").commit();
}
For getting value:
for (int i = 0; i < totalSize; i++) {
myList.add(PreferenceManager.getDefaultSharedPreferences(this)
.getString("number" + i, "0"));
}
NOTE:- totalSize is the size of your array
enjoy coding.............
I think you should try using TinyDB, it's an implementation of SharedPreferences and is very simple to use.
TinyDB tinydb = new TinyDB(context);
tinydb.putList("identifier", list);
You can even save objects:
tinydb.putObject(key, object);
tinydb.putListObject(key, objectsArray);
Related
I am trying to use arraylist.clear and adapter.notifyDataSetChanged() to clear an arraylist the list is cleared successfully but when i try to reload the list again with some data the list is not showing despite the arraylist.size showing the total number of items which is greater than 0. Here is the method to create the initial list
private void getTH(int ID) {
url = "url";
mainAdapterClasses = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
try {
JSONObject jsonObject0 = new JSONObject(response);
String code = jsonObject0.getString("code");;
if (code.matches("200")) {
JSONArray jsonArray = jsonObject1.getJSONArray("items");
if(jsonArray.length() == 0){
txtEmpty.setText(String.format("%s %s", getString(R.string.no), getString(R.string.empty)));
} else {
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass);
}
mainAdapter = new TAdapter(WalletHome.this, mainAdapterClasses);
listView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());
}
}
} catch (JSONException e) {
Toast.makeText(this, ""+getString(R.string.unknown_err), Toast.LENGTH_SHORT).show();
}
})
requestQueue.add(stringRequest);
}
and here is the code that is supposes to reload the list
#Override
public void getRadioButtonListener1(int position) {
WClass wClass = stateClassArrayList.get(position);
wId = wClass.getWId();
if(mainAdapter.getCount() > 0){
mainAdapterClasses.clear();
mainAdapter.notifyDataSetChanged();
getTH(id);
}
}
I tried to log the issue here the method is getting the current total of items everytime i run the method the only issue is that the list is not getting populated with the new data once it is initially cleared.
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());
Any help will be greatly appreciated thanks
At first glance it looks like you are creating and populating the "MainAdapterClass" with the "na" and "aT" variables but not using them anywhere, so you are not really adding items to mainAdapterClasses array.
Second of all, in the for loop you are recreating and setting the adapter each time. I would advise creating and setting the adapter outside of the foor loop once you have your array (mainAdapterClasses) populated with the requested items.
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass);
} //for
mainAdapter = new TAdapter(WalletHome.this, mainAdapterClasses);
listView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged();
txtEmpty.setText("Data Is Here"+mainAdapterClasses.size());
You forgot to add mainAdapterClass to the ArrayList.
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject jsonObject = jsonArray.optJSONObject(k);
String na = jsonObject.optString("na", "NA");
String aT = jsonObject.optString("Type", "NA")
MainAdapterClass mainAdapterClass = new MainAdapterClass();
mainAdapterClass.setName(na);
mainAdapterClass.setType(aT);
mainAdapterClasses.add(mainAdapterClass); // Add this line.
}
Don't setAdapter inside the loop. Just add items and then set the adapter outside the loop.
Also calling notifyDataSetChanged() after setting adapter doesn't make sence.
for (int i = 0; i < jsonArray.length(); i++) {
// ...
}
listview.setAdapter(mainAdapter);
I'm using lib FlexibleAdapter to load JSON API in android studio like this.
public void createHolderSectionsDatabase(int size, int headers) {
databaseType = DatabaseType.MODEL_HOLDERS;
HeaderHolder header = null;
mItems.clear();
int lastHeaderId = 0;
for (int i = 0; i < size; i++) {
header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
mItems.add(newItemHolder(i + 1, header));
}
}
private HeaderHolder newHeaderHolder(int i) {
HeaderModel model = new HeaderModel("H" + i);
model.setTitle("Header " + i);
return new HeaderHolder(model);
}
private ItemHolder newItemHolder(int i, HeaderHolder header) {
ItemModel model = new ItemModel("I" + i);
model.setTitle("Holder Item " + i);
model.setSubtitle("Subtitle " + i);
return new ItemHolder(model, header);
}
Above code only loads the data from looping model item.
I could apply with JSON API such as:
How to change code like:
/* for (int i = 0; i < size; i++) {
header = i % Math.round(size / headers) == 0 ? newHeaderHolder(++lastHeaderId) : header;
mItems.add(newItemHolder(i + 1, header));
}*/
Like this:
listArrayFromJSON = getArrayJSON(); //get JSON with GSON request
mItems.addAll(ListArrayFromJSON,header); //not add`
I dont know your json string structure but, you can update question or inspire from below
public class DataHolder{
private ArrayList<ItemHolder> items; //json object name
private ArrayList<HeaderHolder> headers; //json object name
public Arraylist<ItemHolder> getItems(){
return items;
}
public Arraylist<HeaderHolder> getHeaders(){
return items;
}
}
DataHolder holder = new Gson().fromJson(jsonString, DataHolder.class);
mItems.addAll(holder.getItems());
mHeaders.addAll(holder.getHeaders());
I have no doubt that the contains() method is working correctly but apparently I am doing something wrong. I am working on an android app and I am detecting WiFi and listing the WiFi in a listView. I am attempting to filter out duplicate occurrences of the same Access Point so I am creating an array to keep track of duplicates. Here is my code:
public void getWifi(){
ListView wifiList = (ListView)findViewById(R.id.listView);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
List<ScanResult> apList = wifiManager.getScanResults();
wifiManager.startScan();
List<String> wifees = new ArrayList<>();
//split info into arrays
for(int i=0; i < apList.size(); i++){
String[] daList = String.valueOf(apList.get(i)).split(",");
String info = "";
List<String> SSIDs = new ArrayList<>();
for (String listItem : daList) {
String topic = String.valueOf(listItem.split(":")[0]);
String val = listItem.split(":")[1];
Log.d(TAG, topic);
if (Objects.equals(topic, "SSID")) {
if(SSIDs.contains(val)){
Log.d(TAG, "CONTAINS");
break;
} else {
SSIDs.add(val);
info = val;
}
} else if (Objects.equals(topic, " level")){
String strength = "";
if (Integer.parseInt(val.substring(1)) >= -35) {
strength = "100%";
} else if (Integer.parseInt(val.substring(1)) <= -35 && Integer.parseInt(val.substring(1)) >= -65) {
strength = "50%";
} else {
strength = "1%";
}
info += " " + strength;
}
}
wifees.add(info);
}
assert wifiList != null;
ArrayAdapter apter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, wifees);
wifiList.setAdapter(apter);
}
This is the contents of an apList item or what I get when I call apList.get(i):
SSID: SCHOOL-GUEST, BSSID: 04:04:04:04:04:04, capabilities: [ESS], level: -91, frequency: 2412, timestamp: 72500687089, distance: ?(cm), distanceSd: ?(cm), passpoint: no, ChannelBandwidth: 0, centerFreq0: 0, centerFreq1: 0, 80211mcResponder: is not supported
Here is the output of that code(roughly because it is on a phone and I would rather not include the AP names for security reasons):
SCHOOL-WIRELESS 100%
SCHOOL-SECURE 50%
SCHOOL-GUEST 50%
SCHOOL WIRELESS 1%
SCHOOL_WIRELESS 1%
SCHOOL-SECURE 1%
SCHOOL-GUEST 1%
bxz1872 50%
...
...
...
(so on and so forth)
If I could just get a second opinion that would be great. I feel like I am missing something obvious. Thanks!
.contains doesnt work, because you call List<String> SSIDs = new ArrayList<>(); within for(int i=0; i < apList.size(); i++){. You basically create new empty List for every loop-iteration. You should call it once befor the outer for-loop:
List<String> SSIDs = new ArrayList<>();
for(int i=0; i < apList.size(); i++){
...
}
Please see the below code-
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
List<ElementInformationBean> lstTime = null;
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
lstTime = new ArrayList<ElementInformationBean>();
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
For Printing
for (Map.Entry<DateTime, ArrayList<PanchangaElementInformationBean>> entry : mapTithi.entrySet()) {
DateTime key = entry.getKey();
ArrayList<PanchangaElementInformationBean> values = entry.getValue();
System.out.println("Key = " + key);
for (PanchangaElementInformationBean p: values) {
System.out.print("Values = " + p.getStartTime() + "n");
}
}
I am trying to use the HashMap; Key as dateTime and Value as List. However it always returns when I am iterating and printing the value.
Thanks
Kumar Shorav
Initialize lstTime outside the loop.
Try this code :
Map<DateTime, ArrayList<ElementInformationBean>> mapTithi = new HashMap<DateTime, ArrayList<ElementInformationBean>>();
// Intialize here
List<ElementInformationBean> lstTime = new ArrayList<ElementInformationBean>();
ElementInformationBean curntTithi = null;
ElementInformationBean nextTithi = null;
for (int i = 0; i < lstNakstra.size()-1; i++) {
curntTithi = lstNakstra.get(i);
nextTithi = lstNakstra.get(i+1);
if(curntTithi.getStartTime().toDateMidnight().equals(nextTithi.getStartTime().toDateMidnight()))
{
lstTime.add(curntTithi);
lstTime.add(nextTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
} else {
lstTime.add(curntTithi);
mapTithi.put(curntTithi.getStartTime().toDateMidnight().toDateTime(), (ArrayList<ElementInformationBean>) lstTime);
}
}
On your Getters and Setters of the PanchangaElementInformationBean class change the data type from Date to ArrayList<Date> and add that setStartTime to as bellow so you can get all values from it.
private ArrayList<Date> startTime;
public ArrayList<Date> getStartTime() {
return startTime;
}
public void setStartTime(Date item) {
if (startTime == null) {
startTime = new ArrayList<Date>();
}
this.startTime.add(item);
}
So while you iterate you can get all the values from the ArrayList
And add this on the main printing for loop to print individual Date from ArrayList
for (Date startTime : p.getStartTime()) {
System.out.println(startTime);
}
And Initialize lstTime = new ArrayList<ElementInformationBean>(); on above the For Loop so that you can add many elements are else it will add only one for loop instance value repeatedly to the list.
If you want to accumulate elements in a list used as value of a map, you have to use this approach:
List<...> list = map.get( key );
if( null == list ) {
list = new ...;
map.put( key, list );
}
list.add( ... );
I would like to know how to use MultiSelectListPreference preference in code.
The following code is taken from the API examples file PreferencesFromCode.java, if someone could give a similar example for MultiSelectListPreference you would make my day :)
// List preference
ListPreference listPref = new ListPreference(this);
listPref.setEntries(R.array.entries_list_preference);
listPref.setEntryValues(R.array.entryvalues_list_preference);
listPref.setDialogTitle(R.string.dialog_title_list_preference);
listPref.setKey("list_preference");
listPref.setTitle(R.string.title_list_preference);
listPref.setSummary(R.string.summary_list_preference);
dialogBasedPrefCat.addPreference(listPref);
I couldn't find any examples online, but I put this together and it works.
Edit: This solution will only work on ICS+. Honeycomb completely ignores .setValues() and the HashSet passed to the listener contains different values. This is a known bug, but I hope this will help people wanting to implement in Android v4+
MultiSelectListPreference listPreference = new MultiSelectListPreference(context);
listPreference.setTitle(R.string.configure_category_title);
listPreference.setDialogTitle(R.string.configure_category_title);
listPreference.setSummary(R.string.configure_category_summary);
listPreference.setEntries(R.array.configure_category_array);
listPreference.setEntryValues(new CharSequence[]{
ProcessList.PREF_SERVICES + mAppWidgetId,
ProcessList.PREF_INACTIVE + mAppWidgetId,
ProcessList.PREF_INTERNAL + mAppWidgetId
});
//Create a Set<String> with list items that should be selected
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
boolean showServices = sharedPref.getBoolean(ProcessList.PREF_SERVICES + mAppWidgetId, true);
boolean showInactive = sharedPref.getBoolean(ProcessList.PREF_INACTIVE + mAppWidgetId, true);
boolean showInternal = sharedPref.getBoolean(ProcessList.PREF_INTERNAL + mAppWidgetId, true);
String[] strings = new String[3];
int cnt = 0;
if (showServices)
strings[cnt++] = ProcessList.PREF_SERVICES + mAppWidgetId;
if (showInactive)
strings[cnt++] = ProcessList.PREF_INACTIVE + mAppWidgetId;
if (showInternal)
strings[cnt] = ProcessList.PREF_INTERNAL + mAppWidgetId;
Set<String> mySet = new HashSet<String>();
Collections.addAll(mySet, strings);
//Add the set
listPreference.setValues(mySet);
//Listen for changes, I'm not sure if this is how it's meant to work, but it does :/
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object o) {
HashSet hashSet = (HashSet) o;
Iterator stringIterator = hashSet.iterator();
boolean[] states = {false, false, false};
String prefString;
while (stringIterator.hasNext()) {
prefString = (String) stringIterator.next();
if (prefString == null)
continue;
if (prefString.compareTo(ProcessList.PREF_SERVICES + mAppWidgetId) == 0)
states[0] = true;
else if (prefString.compareTo(ProcessList.PREF_INACTIVE + mAppWidgetId) == 0)
states[1] = true;
else if (prefString.compareTo(ProcessList.PREF_INTERNAL + mAppWidgetId) == 0)
states[2] = true;
}
PreferenceManager
.getDefaultSharedPreferences(getActivity())
.edit()
.putBoolean(ProcessList.PREF_SERVICES + mAppWidgetId, states[0])
.putBoolean(ProcessList.PREF_INACTIVE + mAppWidgetId, states[1])
.putBoolean(ProcessList.PREF_INTERNAL + mAppWidgetId, states[2])
.commit();
return true;
}
});
preferenceCategory.addPreference(listPreference);