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++){
...
}
Related
I want to get number of total apps in android and make sure that this is not working.
int numberOfInstalledApps = getPackageManager().getInstalledApplications(0).size();
This always returns 138,
If I uninstall a app then returns 138
If I download an app then returns 138.
To get the non-system applications installed on the device, you can do the following :
public static ArrayList<String> getAllInstalledApps() {
ArrayList<String> applicationsList = new ArrayList<>();
List<PackageInfo> packageList = getPackageManager()
.getInstalledPackages(0);
for (int i=0; i < packageList.size(); i++) {
PackageInfo packInfo = packageList.get(i);
if ((packInfo.applicationInfo.flags
& ApplicationInfo.FLAG_SYSTEM) == 0) {
String applicationName = packInfo.applicationInfo
.loadLabel(getPackageManager()).toString();
applicationsList.add(applicationName);
Log.e("App >" + Integer.toString(i), applicationName);
}
}
return applicationsList;
}
You can then get the list by doing:
int number = getInstalledApps().size();
You can also start any of the applications by calling:
Intent callAppIntent = new Intent(Intent.ACTION_MAIN, null);
callAppIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List appsList = context.getPackageManager()
.queryIntentActivities(callAppIntent, 0);
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 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);
how can i scroll a view (recyclerview) in relation to my tts,
ive looked at onUtterance but it seems to only have a start and stop listener, so i need to think outside the box, i give my tts a string from an Arraylist like this
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++)
{
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
speakWords(words);
I was thinking about cutting the string up into sections and giving it to the TTS one string at a time and move the view as I go. I already give my gridlayout manager an int for the amount of columns (called columns).
The array list adds a comma after every word, so I was thinking something like
find the nth/(column) comma
split the string
check if tts is speaking and listen for onUtterance onDone to pass new string
read the string
move the view
and keep doing this until theres no words left and coding for the remainder % im not sure how to do all of that so if anyone wants to help feel free, (I think Im looking at StringUtils and creating each smaller string with a for loop and passing them to the tts in onUtteranceListener onDone, but im still a little new to android), but mainly does anyone have a better way
okay this is what i have so far but it could probably use some work im still an amateur, I've split the string into blocks based on the size of the screen, and the handler that scrolls the screen relies on the amount of letters in each broken up string, also the smoothscrolltoposition is scrolling a custom layout manager that scrolls pretty slowly im having an issue though where on some devices the array list counting the words will only reach 20 not sure why but ill ask and hopefully update this when ive fixed it so here is my speak and move method
public void speakAndMove(){
final ArrayList<String> list = new ArrayList<>();
SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(0);
for (int i = 0; i < SpeakRecyclerGrid.recyclerView.getChildCount(); i++) {
list.add(((EditText) SpeakRecyclerGrid.recyclerView.getChildAt(i)).getText().toString());
}
Integer numOfWords = list.size();
words = list.toString();
Integer count = 0;
Integer startPoint = 0;
scrollPos = 0;
final Integer speed = words.length() * 15;
Integer leftOver = 0;
final int columns = getResources().getInteger(R.integer.grid_columns);
System.out.println(numOfWords);
ArrayList<String> arrayList = new ArrayList<>();
if (list.size() <= columns) {
if (words.contains("[]")) {
speakWords("");
} else if (words.contains(", 's")) {
formatString = words.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (words.contains(", ing")) {
formatString = words.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(words);
}
}
if (list.size()>=columns) {
for (int i = 0; i < words.length(); i++) {
if (words.charAt(i) == ',') {
count++;
if (count == columns) {
String ab = words.substring(startPoint, i + 1);
//speakWords(ab);
if (ab.contains(", 's")) {
formatString = ab.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab.contains(", ing")) {
formatString = ab.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab);
}
startPoint = i + 1;
count = 0;
leftOver = words.length() - startPoint;
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("main string"+" scroll " + scrollPos + " startpoint " + startPoint +" speed " + speed);
}
}
if (leftOver > 0) {
String ab2 = words.substring(startPoint, words.length());
//speakWords(ab2);
if (ab2.contains(", 's")) {
formatString = ab2.replaceFirst(", 's", "'s");
speakWords(formatString);
} else if (ab2.contains(", ing")) {
formatString = ab2.replaceFirst(", ing", "ing");
speakWords(formatString);
} else {
speakWords(ab2);
}
//SpeakGrid.recyclerView.getLayoutManager().scrollToPosition(scrollPos);
System.out.println("leftovers "+ leftOver + " scroll " + scrollPos + " startpoint " + startPoint +" count " + scrollPos);
count = 0;
//scrollPos = 0;
}
}
final Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
scrollPos = scrollPos + columns;
SpeakGrid.recyclerView.getLayoutManager().smoothScrollToPosition(SpeakGrid.recyclerView, null ,scrollPos);
System.out.println("position "+ scrollPos + " speed " + speed + " list size " + list.size());
if (scrollPos < list.size())
h.postDelayed(this,speed);
// close this activity
}
}, speed);
}
I'm trying obtain all the names from one file and all the attendances from another then calculate the average attendance. I know the att bit in the calculation is completely wrong but I could not work it out.
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
}
double attendance = 0; //start attendance as 0
for (int i = 0; i < att.length; i++)
{
attendance += att[i];
}
return attendance / att.length;
}
I am guessing that the Match class will have a team name and attendance(an array list). Just like getting the team name, there should be a get to get the attendance array list .Assuming this you can try the below approach:
{
ArrayList<Match> ourList = new ArrayList(teams);
ArrayList<Match> teamsAttendance = new ArrayList<Match>();
//to store the attendance mean for each team
ArrayList<double> teamAttendanceMean = new ArrayList<double>();
//to store the attendance values of team
ArrayList<double> tempAttendance= new ArrayList<double>();
//declare outside
double attendance = 0;
for (Match att : ourList)
{
if (att != null && att.getTeamName().equals(team.getName()))
{
teamsAttendance.add(att);
}
attendance = 0;// assign 0
tempAttendance = att.getTeamAttendance();
for (int i = 0; i < tempAttendance.size(); i++)
{
attendance += tempAttendance [i];
}
//storing the mean value
teamAttendanceMean.add(attendance/tempAttendance.size());
}
}
Let me know if any of my assumptions are wrong and also post information on the Match class if so.