ConcurrentModificationException when I iterate on ArrayList - java

I want to iterate on an ArrayList called localWifiList that contains the wifi networks detected by a wifi scan.
For every element of the ArrayList I want to run a query to get all tuples in the database with that specific mac address, create a new object and add this object into a new arrayList called wifiFromDatabase.
I wrote this code:`
ArrayList<wifiList> wifiFromDatabase = new ArrayList<wifiList>();
ArrayList<wifiList> localWifiList = ScanService.wifiArraList;
//field to read the values of wifi query results
String mac;
String ssid;
String cid;
String signalLevel;
String capabilities;
String rssi;
String lat, lng;
String date;
String frequency;
int flagInt;
Cursor cursor;
Iterator<wifiList> iterator = localWifiList.iterator();
while(iterator.hasNext()){
wifiList element = (wifiList) iterator.next();
cursor = MainActivity.getDBOperationHelper().getWifiTupleByMac
(MainActivity.getDBOperationHelper().getReadableDatabase(), element.getMacAddress());
if(cursor.getCount()>0){
if (cursor .moveToFirst()) {
while (cursor.isAfterLast() == false) {
mac = cursor.getString(cursor.getColumnIndex(DBOperationHelper.MAC));//
ssid = cursor.getString(cursor.getColumnIndex(DBOperationHelper.SSID));//
capabilities = cursor.getString(cursor.getColumnIndex(DBOperationHelper.CAPABILITIES));//
frequency = cursor.getString(cursor.getColumnIndex(DBOperationHelper.FREQUENCY));//
cid = cursor.getString(cursor.getColumnIndex(DBOperationHelper.CELL_ID_UMTS));//
signalLevel = cursor.getString(cursor.getColumnIndex(DBOperationHelper.SIGNAL_LEVEL_WIFI));//
rssi = cursor.getString(cursor.getColumnIndex(DBOperationHelper.RSSI));
lat = cursor.getString(cursor.getColumnIndex(DBOperationHelper.GPS_LATITUDE_WIFI));//
lng = cursor.getString(cursor.getColumnIndex(DBOperationHelper.GPS_LONGITUDE_WIFI));//
date = cursor.getString(cursor.getColumnIndex(DBOperationHelper.DATE_WIFI));//
flagInt = cursor.getInt(cursor.getColumnIndex(DBOperationHelper.FLAG));
wifiList objectFromDb = WifiPhoneConfiguredNetworkHandler.CreateProperlyWifiListObject(ssid, capabilities, frequency, signalLevel, ConnectionPointAnalyzer.INVALID_ID_WIFI, signalLevel,
mac, rssi, date, cid, lat, lng, flagInt, false);
wifiFromDatabase.add(objectFromDb);
cursor.moveToNext();
}
}
}else{ //the database has not tuples with this mac
Log.d(ConnectionPointAnalyzer.LOG_TAG, "OracoloBrain.java/AllInterfacesActived: no tuples found in the db with mac = "+element.getMacAddress()+
" ssid = "+element.getSsid());
}
} `
where the method CreateProperlyWifiListObject create an wifiList object given the fields passed as arguments.
I read many thread about this issues, but nothing to do. I try also with synchronized on the arrayList.
The exception is thrown by iterator.next() command.

Try to create a copy:
ArrayList<wifiList> localWifiList = new ArrayList<wifiList>(ScanService.wifiArraList);

Related

zoom sdk for android: can't join as a host

i already inputted all the necessary parameters for it to work according to the docs and the forums but it just can't seem to work on me
private void joinMeeting(Context context, String meetingNumber,String zak, String userName, String usID){
int ret = -1;
MeetingService meetingService = ZoomSDK.getInstance().getMeetingService();
JoinMeetingOptions options = new JoinMeetingOptions();
//JoinMeetingParams params = new JoinMeetingParams();
//params.displayName=userName;
//params.meetingNo =meetingNumber;
//params.password=meetingPassword;
//meetingService.joinMeetingWithParams(context,params,options);
StartMeetingParamsWithoutLogin params = new StartMeetingParamsWithoutLogin();
params.userId = usID; // Based on this id we are able to start the meeting as host
params.userType = MeetingService.USER_TYPE_API_USER;
params.displayName = userName;
params.zoomAccessToken = zak; //getting the zoom access token from start_url
params.meetingNo = meetingNumber; // meetingNo, getting this from create meeting api response
ret = meetingService.startMeetingWithParams(context,params,options);
Log.e("Start Meeting As Host", "===startMeetingWithNumber====ret=" + ret);
}
i tried all generating more meeting using my web sdk but it wont work either

Trying to pull plain text data to use in a service

I'm creating an app for an android mobile computer that can take the data scanned and convert a specified character to another. The way it currently works, I manually code in what characters to look for and convert to:
public String specialWorkFor(String originalData, String codeType ){
String[] targetStr = {"1", "2", "3"};
String[] replaceStr = {"a","b","c"};
String newData = "";
newData = originalData;
newData = ReplaceText(originalData,targetStr,replaceStr);
return newData;
}
private static String ReplaceText (String originalData, String[] targetStr, String[] replaceStr ){
String newData = "";
String newDataTmp = "";
newData = originalData;
for (int i = 0; i < targetStr.length; i++){
newDataTmp = newData.replace(targetStr[i], replaceStr[i]);
newData = newDataTmp;
}
return newData;
}
This works fine, but ideally I'd like to have an interface where I can just type into a plain text field and use the values from there to determine what characters get converted.
After creating the layout, I've tried doing this:
//Inputs
Context context1 = getApplicationContext();
Activity act1=(Activity)context1;
EditText codein = (EditText) act1.findViewById(R.id.input);
String in = codein.getText().toString();
//Outputs
Context context2 = getApplicationContext();
Activity act2=(Activity)context2;
EditText codeout = (EditText) act2.findViewById(R.id.output);
String out = codeout.getText().toString();
public String specialWorkFor(String originalData, String codeType ){
//String[] targetStr = {in};
//String[] replaceStr = {out};
String newData = "";
newData = originalData;
newData = ReplaceText(originalData,targetStr,replaceStr);
return newData;
}
Where I use:
Context context1 = getApplicationContext();
Activity act1=(Activity)context1;
EditText codein = (EditText) act1.findViewById(R.id.input);
String in = codein.getText().toString();
to pull values from the activity where I enter in my values. Issue is when I scan I get the error:
Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
I am unsure where to go from here. Any thoughts?
You cannot cast application context to an activity.
Create class Storage like this:
public class Storage {
public static final Storage instance = new Storage();
public String codeIn = "";
public String codeOut = "";
}
Add a textWatcher to both edittexts, and inside ontextchanged add :
Storage.instance.codeIn = whatever is in coresponding edittext
Inside the service you can get those values the same way:
String in = Storage.instance.codeIn
Also note that those values mast be set before the service uses them)))

Java REST API upon building string after get request replace null values with string vale

I am currently working on a Java application where I have an AsyncTask function get data from an API, then have a line reader and string builder create a large string, which I then pass to the postExecute function where I convert that string into a JSON object. I have tried creating a function that takes the string before post execute and replaces all null with "N/A", I have also tried checking in the String builder function but neither seem to make any changes to the null value. Here is an example of what the code looks like. I believe the error occurs when The string is converted into the JSON Object. This is a school project and I am not allowed to use external libraries.
String Builder:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
if (line.contains(null) || line.contains(""))
line += "N/A";
else
continue;
builder.append(line + "\n");
}
replaceNull Function:
public String removeUnwantedVal(String message) {
if (message.contains("null")) {
String replacement = "N/A";
message.replaceAll(null, replacement);
}
return message;
}
Post Execute JSON Object:
protected void onPostExecute(String message) {
TextView tv = findViewById(R.id.display);
System.out.println(message);
try {
JSONObject jsonAddress = new JSONObject(message);
// DISPLAY INFORMATION
String requesterIP = jsonAddress.getString("requester-ip");
String execTime = jsonAddress.getString("execution-time");
ipInfo.setIPAndTime(requesterIP, execTime);
// GEOGRAPHY
JSONObject geo = jsonAddress.getJSONObject("geo");
String countryName = geo.getString("country-name");
String capital = geo.getString("capital");
String iso = geo.getString("country-iso-code");
String city = geo.getString("city");
double longitude = geo.getDouble("longitude");
double latitude = geo.getDouble("latitude");
location = new Location(countryName, capital, iso, city, longitude, latitude);
// CURRENCY
JSONObject currency = jsonAddress.getJSONObject("currency");
String currencyNativeName = currency.getString("native-name");
String currencyCode = currency.getString("code");
String currencyName = currency.getString("name");
String currencySymbol = currency.getString("symbol");
Currency = new Currency(currencyNativeName, currencyCode, currencyName, currencySymbol);
// ASN
JSONObject asn = jsonAddress.getJSONObject("asn");
String asnName = asn.getString("name");
String asnDomain = asn.getString("domain");
String asnOrganization = asn.getString("organization");
String asnCode = asn.getString("asn");
String asnType = asn.getString("type");
ASN = new ASN(asnName, asnDomain, asnOrganization, asnCode, asnType);
// TIMEZONE
JSONObject timezone = jsonAddress.getJSONObject("timezone");
String timezoneName = timezone.getString("microsoft-name");
String dateTime = timezone.getString("date-time");
String ianaName = timezone.getString("iana-name");
Timezone = new Timezone(timezoneName, dateTime, ianaName);
// SECURITY
JSONObject security = jsonAddress.getJSONObject("security");
boolean isCrawler = security.getBoolean("is-crawler");
boolean isProxy = security.getBoolean("is-proxy");
boolean isTor = security.getBoolean("is-tor");
Security = new Security(isCrawler, isProxy, isTor);
container = new IPContainer(ipInfo, Currency, location, Security, ASN, Timezone);
tv.setText(container.displayGeneral());
} catch (JSONException e) {
tv.setText(e.toString());
e.printStackTrace();
}
}
I have resolved the issue. When I was getting the code I thought that null values could not be displayed, this was incorrect. The problem was that I was trying to create an object out of null, sometimes the value came back as null instead of as an object. Sorry, beginner coder :)

List DataModel reads just the last element

I have a database created with location updates and in the database there is a bunch of locations x and y. and in the second method readFirestore() reads the location data and compares the favorite locations which came from sqlite database and if the favorite location is near the data from firestore it writes the campaign name which is on the same location to another database. But when I want to compare the favorite location in the firestore methot, there is just the last item of the database. I looked with the Log.
Code 1:
public List<DataModel> listFavoriteLocation(){
db = new DatabaseHelper(this);
SQLiteDatabase mydb = db.getWritableDatabase();
List<DataModel> data=new ArrayList<>();
Cursor csr = mydb.rawQuery("select * from "+TABLE+" ;",null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (csr.moveToNext()) {
dataModel= new DataModel();
String FAVCurrentLocationLAT = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLAT"));
String FAVCurrentLocationLONG = csr.getString(csr.getColumnIndexOrThrow("FAVCurrentLocationLONG"));
dataModel.setFAVCurrentLocationLAT(FAVCurrentLocationLAT);
dataModel.setFAVCurrentLocationLONG(FAVCurrentLocationLONG);
stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
return data;
}
Code 2:
public void readFirestore() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("campaigns")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
private String FSname,FScityLAT,FScityLONG,FScampaignStartDate,FScampaignEndDate;
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
for (QueryDocumentSnapshot document : task.getResult()) {
String name = document.getString("name");
String cityLAT = document.getString("cityLAT");
String cityLONG = document.getString("cityLONG");
String campaignStartDate = document.getString("campaignStartDate");
String campaignEndDate = document.getString("campaignEndDate");
this.FSname = name;
this.FScityLAT = cityLAT;
this.FScityLONG = cityLONG;
this.FScampaignStartDate = campaignStartDate;
this.FScampaignEndDate = campaignEndDate;
listFavoriteLocation();
String FS_FAVCurrentLocationLAT = List_FAVCurrentLocationLAT;
String FS_FAVCurrentLocationLONG = List_FAVCurrentLocationLONG;
Log.i("hellolist",""+List_FAVCurrentLocationLAT); // just writes the last loc item from sqlite
double FS_FAVCurrentLocationLAT_double = Double.parseDouble(FS_FAVCurrentLocationLAT); // Fav Loc DB
double FS_FAVCurrentLocationLONG_double = Double.parseDouble(FS_FAVCurrentLocationLONG); double FScityLAT_double = Double.parseDouble(FScityLAT); // Campaign Loc Firestore LAT
double FScityLONG_double = Double.parseDouble(FScityLONG);
double theta = FScityLONG_double - FS_FAVCurrentLocationLONG_double;
double dist = Math.sin(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.sin(Math.toRadians(FScityLAT_double)) + Math.cos(Math.toRadians(FS_FAVCurrentLocationLAT_double)) * Math.cos(Math.toRadians(FScityLAT_double)) * Math.cos(Math.toRadians(theta));
dist = Math.acos(dist);
dist = Math.toDegrees(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344;
if (dist <= 0.5) // 500 meter
{
SQLiteQueryFavCampaign = "INSERT OR REPLACE INTO myTable3(FAVCampaignName, FAVCampaigncampaignStartDate, FAVCampaigncampaignEndDate)" + " VALUES('"+FSname+"','"+FScampaignStartDate+"','"+FScampaignEndDate+"');";
SQLITEDATABASEFavCampaign.execSQL(SQLiteQueryFavCampaign);
Log.i("helloname",""+FSname);
}
}
} else {
}
}
});
Toast.makeText(CampaignActivity.this,"Creating", Toast.LENGTH_SHORT).show();
}
If I understand correctly: the listFavoriteLocation method properly retrieves the data you're expecting from the database. If you take a look at the rest of your code, you'll see that you are iterating over the list of data and overwriting your instance variables with them, one-by-one, until the list has been fully iterated over, meaning you will only preserve the last element in your instance once you've left the method.
So, to be clear, the following block will properly log every element, but only the values of the last element will be preserved in the two instance variables you're using (FAVCurrentLocationLAT and FavCurrentLocationLong):
for (DataModel mo:data ) {
this.List_FAVCurrentLocationLAT = mo.getFAVCurrentLocationLAT();
this.List_FAVCurrentLocationLONG = mo.getFAVCurrentLocationLONG();
Log.i("helloLAT",""+List_FAVCurrentLocationLAT); //OK
Log.i("helloLONG",""+List_FAVCurrentLocationLONG); //OK
// This section writes the favorite locations seperately to the log.
}
What you need to do is use the returned data list being loaded in the listFavoriteLocation method, and then manipulate it in the following code as you wish.
So, for example:
List<DataModel> data = listFavoriteLocation();
for (int i = 0; i < data.size(); i++) {
DataModel dataModel = data.get(i);
log.i("Data model "+i+": "+dataModel);
// Do work on each data model element here
}

Use csv data as string java

This maybe simple but java isn’t really my thing but I'm working with a java API.
I need to parse a csv file and use the values as strings.
CSV file:
Mac,device,level ,key number,key function ,name,number,prim
01:1A:E8:84:9D:27,0,0,1,31,line,441865945218,TRUE
01:1A:E8:84:9D:27,0,0,2,51,dss,441865985452,FALSE
each row need to be read seprately so something like.
Read first row of csv
Assign values to strings (e.g. mac = 01:1A:E8:84:9D:27 device = 0 and so on)
Run "code" using these strings
Read second row of csv
So on till end of csv.
Thanks
I have tried csvreader but I'm not able to use the strings outside of the while function and it does not read line by line.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
while (phones.readRecord()){
String deviceID = phones.get("Mac");
String device = phones.get("device");
String level = phones.get("level");
String keynumber = phones.get("key number");
String keyfunction = phones.get("key Function");
String label = phones.get("name");
String e164 = phones.get("number");
String prim = phones.get("prim");
}
As you are new to Java, whatever you are doing, looks like it reads the file line by line. But as you are defining the Strings in while loop, you won't be able to access it outside.
If you want to read all lines and store in Strings, you should probably take array for all of them and define them outside the while loop, add values in the loop and then you'll be able to use it.
Or just create a Phone class:
public class Phone{
String deviceId;
String device;
......etc...
//setters and getters
}
And take an array of it outside while. Something like this:
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
List<Phone> phonesArr=new ArrayList<Phone>();
while (phones.readRecord())
{
Phone phone=new Phone();
phone.setDeviceId(phones.get("Mac"));
phone.setDevice(phones.get("device"));
.....
phones.add(phone);
}
// array phones will be accessible here
Hope that helps!
You have to declare the Strings outside of the loop. Otherwise the String variables would be loop scoped.
CsvReader phones = new CsvReader("dls.csv");
phones.readHeaders();
String deviceID;
String device;
String level;
String keynumber;
String keyfunction;
String label;
String e164;
String prim;
while (phones.readRecord()){
deviceID = phones.get("Mac");
device = phones.get("device");
level = phones.get("level");
keynumber = phones.get("key number");
keyfunction = phones.get("key Function");
label = phones.get("name");
e164 = phones.get("number");
prim = phones.get("prim");
}
See:
Scopes tutorial
Javadoc: Variables
In the end I just called the funtion from the while loop.
while (phones.readRecord()) {
deviceID = phones.get("Mac");
Device = phones.get("device");
Level = phones.get("level");
Keynumber = phones.get("key number");
Keyfunction = phones.get("key function");
Label = phones.get("name");
E164 = phones.get("number");
Prim = phones.get("prim");
tools connect = new tools();
connect.connect();
connect.setkeys(deviceID,Device,Level,Label,Keynumber,Keyfunction,E164,Prim);
//System.out.println(Prim);
}
phones.close();

Categories

Resources