Trying to pull plain text data to use in a service - java

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

Related

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

I want to data type Conversion in a row in android

Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}

Inserting a value into a URL in android studio?

I sent data from Activity A to Activity B through means of an intent.
I then extracted the results of the intent via the following.
String IdString = questionData.getString("id");
TextView mstudentId = (TextView) findViewById(R.id.ID);
mstudentId.setText(IdString);
I would now like to take the value of IdString which is equal to the value of the string "id" and place it inside a Url. For example,
final static String URL_ANSWER = "http//:myFake/(IdString)/Url"
How do I go about doing this in Android Studio?
Like this,
final static String URL_ANSWER = "http//:myFake/" + IdString + "/Url";
OR
UPDATE
String IdString = questionData.getString("id");
TextView mstudentId = (TextView) findViewById(R.id.ID);
mstudentId.setText(IdString);
final static String URL_ANSWER = "http//:myFake/" + mstudentId.getText() + "/Url";

Transferring a 2D array from one class to another

I am attempting to take all the information that added by the user in the text fields, and then add them a 2D array. I have accomplish that by doing this:
int minorinput = JOptionPane.showConfirmDialog(frame, panel1, "Choose Minor Stats", JOptionPane.OK_CANCEL_OPTION);
if(minorinput == JOptionPane.OK_OPTION)
{
int [][] pureMR = new int [4][4];
pureMR[0][0] = Integer.parseInt(Melee.getText());
pureMR[1][0] = Integer.parseInt(Ranged.getText());
pureMR[2][0] = Integer.parseInt(RC.getText());
pureMR[3][0] = Integer.parseInt(Negotiation.getText());
pureMR[0][1] = Integer.parseInt(Dodge.getText());
pureMR[1][1]= Integer.parseInt(Perception.getText());
pureMR[2][1] = Integer.parseInt(Will.getText());
pureMR[3][1] = Integer.parseInt(Procure.getText());
pureMR[0][2] = Integer.parseInt(rideBox.getText());
pureMR[1][2] = Integer.parseInt(rideBox2.getText());
pureMR[2][2] = Integer.parseInt(artBox.getText());
pureMR[3][2] = Integer.parseInt(art2.getText());
pureMR[0][3] = Integer.parseInt(knowledgeBox.getText());
pureMR[1][3] = Integer.parseInt(knowledge2Box.getText());
pureMR[2][3] = Integer.parseInt(infoBox.getText());
pureMR[3][3] = Integer.parseInt(info2Box.getText());
But I can't figure out how to transfer the array to a different class, where it will be used in an object constructor that will allow me to print via the objects toString method.
How should I be going about transferring the 2D array from class to class?
Class I want to add the Array to:
if(pureinput == JOptionPane.OK_OPTION)
{
String name = nameBox.getText();
String age = ageBox.getText();
String gender = genderBox.getText();
String bloodType = bloodBox.getText();
String height = heightBox.getText();
String weight = weightBox.getText();
String zodiac= zodiacBox.getText();
String work = workBox.getText();
String cover = coverBox.getText();
String breed = "Pure";
String sydrome = syndrome1Box.getText();
int[] pureBS = new int[4];
pureBS[0] = Integer.parseInt(bodyBox.getText());
pureBS[1] = Integer.parseInt(senseBox.getText());
pureBS[2] = Integer.parseInt(mindBox.getText());
pureBS[3] = Integer.parseInt(skillBox.getText());
int[] pureSS = new int[6];
pureSS[0] = Integer.parseInt(mHPBox.getText());
pureSS[1] = Integer.parseInt(stockBox.getText());
pureSS[2] = Integer.parseInt(savingsBox.getText());
pureSS[3] = Integer.parseInt(initBox.getText());
pureSS[4] = Integer.parseInt(moveBox.getText());
pureSS[5] = Integer.parseInt(dashBox.getText());
String origin = orginBox.getText();
String exp = ExperienceBox.getText();
String encounter = EncounterBox.getText();
String awake = AwakeningBox.getText();
int eRate = Integer.parseInt(EncroachmentRateBox.getText());
String impulse = ImpulseBox.getText();
int eRate2= Integer.parseInt(EncroachmentRateBox2.getText());
Character pure = new Character(name,age,bloodType,gender, height,weight,zodiac,work,cover,
breed,sydrome,pureBS, pureSS,origin,exp,encounter,awake,eRate,
impulse,eRate2, //Needs a 2D array here);
System.out.println(pure.pureToString());
It creates this dialog box.
The simplest way: simply call a setter method, and pass the array into the instance:
if(minorinput == JOptionPane.OK_OPTION) {
int [][] pureMR = new int [4][4];
// code to fill array
// assuming your OtherClass has this type of setter method...
// because if it doesn't, it NEEDS one.
otherInstance.setPureMr(pureMR);
Where you get your reference to the otherInstance instance will depend totally on how your program is structured, information that we are not privy to at this moment.
Having said this, I do have to wonder if your 2D array is a kludge, if you're far better off creating a class to hold this information, and then passing an object of this class into your other instance.

ConcurrentModificationException when I iterate on ArrayList

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

Categories

Resources