I have this bit of code that show me the text from the json file, but I would like to check the text if there's a specific word in it.
Here's my code :
if (currentLocation.distanceTo(myModel.getNearest()) < 500) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
}
the myModel.getNearest()) is here :
public Location getNearest(){
nearest = cameras.get(0);
return nearest;
}
and JSON file :
{
"lng":0.18077 ,
"lat": 43.00854 ,
"name":"Orange Store",
"tribe":"1",
"id":"1",
"verified":"1"
},
I've tried this but didn't work :
if (currentLocation.distanceTo(myModel.getNearest()) < 500) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
if (seriousWarning.equals("Orange"))
sign.setText("JAckbot");
}
any help is much appreciated.
Simply store text in any String variable like:
String s1 = [your text];
if(s1.contains([specific word]))
{
do something if text contains specific word
}else
{
do something is text do not contain word
}
Related
Hello every one am newly in app development ,I have a json data and there is key (order_id) some time order_id value is return ("order_id": "188") but some time return Integer like that ("order_id": 188) .is there any way to find that is return string or Integer in ios(swift) and android both thanks
here is example of json response
"orders": [
{
"order_id": "188",
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
And some time like that
"orders": [
{
"order_id": 188,
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
Android :
Object order_id = jsonarray.getJsonObject(0).getInt("order_id");
Object invoice_id = jsonarray.getJsonObject(0).getString("invoice_id");
Object order_status= jsonarray.getJsonObject(0).getInt("order_status");
if(order_id instanceOf String)
// do what you want
.....
May be this will help you
Swift
You can use like:
let str = "188" // Your response string or Int here
var sInt:Int = Int()
// Check if 's' is a String
if str is String {
print("Yes, it's a String")
sInt = Int(str)!
print(sInt)
}else{
print("Not a string")
}
Another Way is:
You can forcefully convert it to string and then Int for safer side
let str = "\(strResponse)" // Your String here
let strToInt = Int(str)
You could decode it as string even when it's an integer with Swift 4:
struct Order: Decodable {
private enum CodingKeys: String, CodingKey {
case orderId = "order_id"
}
let orderId: String
init(from decoder: Decoder) throws {
let container = try? decoder.container(keyedBy: CodingKeys.self)
if let orderId = try container?.decodeIfPresent(String.self, forKey: .orderId) {
self.orderId = orderId
} else if let orderId = try container?.decodeIfPresent(Int.self, forKey: .orderId) {
self.orderId = String(orderId)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Couldn't decode orderId"
))
}
}
}
I am stuck in a small problem. I have text retrieved from the permission window.
Now I found out a way to retrieve the app name . This is how I did it:
private String Namer(String parse){
if(parse.length() > 30) {
parse = parse.substring(parse.indexOf("********") + 6, parse.length());
parse = parse.substring(0, parse.indexOf("*******"));
return parse;
} else {
return parse;
}
}
and this is how i use it:
List<AccessibilityNodeInfo> NodeInfo;
AccessibilityNodeInfo nodeInfo = event.getSource();
for (Map.Entry<OriginalPermissions, String> permissions :
detect.entrySet()) {
NodeInfo = nodeInfo.findAccessibilityNodeInfosByText(permissions.getValue());
Log.d("Information", Namer(Namer(String.valueOf(NodeInfo))));
}
But the problem is that the permission window text can be different. Is there any way in which I could just retrieve the bold text from the permission window?
Thanks
As you see (source code), title of GrantPermissionsActivity is a Spanned text. Instead relying on the surrounding text you can get the value of first span (with bold text) using such method:
public String getFirstSpanValueFromTitle(Spanned text) {
StyleSpan[] spans = text.getSpans(0, text.length(), StyleSpan.class);
if (spans.length > 0) {
int start = text.getSpanStart(spans[0]);
int end = text.getSpanEnd(spans[0]);
return String.valueOf(text.subSequence(start, end));
}
return "";
}
Otherwise, you will need to get the value of the permission_warning_template resource string for each language and hardcode it in you code.
UPDATE:
Example how to get title text from AccessibilityEvent object:
String pkgName = event.getPackageName().toString();
if ("com.google.android.packageinstaller".equals(pkgName)) {
AccessibilityNodeInfo root = event.getSource();
List<AccessibilityNodeInfo> nodes =
root.findAccessibilityNodeInfosByViewId("com.android.packageinstaller:id/permission_message");
if (nodes.size() > 0) {
Log.e(TAG, "First span value: " + getFirstSpanValueFromTitle((Spanned) nodes.get(0).getText()));
}
}
I want show list of strings in TextView and I get this list from server.
List from json :
"stars": [
{
"name": "Elyes Gabel"
},
{
"name": "Katharine McPhee"
},
{
"name": "Robert Patrick"
}
]
I want show this names such as this sample :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
I should setText from this TextView in Adapter.
With below code I can show name :
model.get(position).getStars().get(0).getName();
But just show me Elyes Gabel !!!
I want show me such as this :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
How can I it? Please help me
Here is the correct answer you might be after,
Lets just say you have the above JSON and you have converted that in a String array.
So array will look something like below:
String stars[] = {Elyes Gabel, Katharine McPhee, Robert Patrick}
TextView textView = // initialise the textview here or however you do.
StringBuilder builder = new StringBuilder();
for (String star: stars) {
builder.append(star);
builder.append(", ");
}
textView.setText(builder.toString());
You will get the desired output...
You need to loop through all "Star" elements and build the string yourself. You should have something like this:
String concatenatedStarNames = "";
List<Star> stars = model.get(position).getStars(); // I assume the return value is a list of type "Star"!
for (int i = 0; i < stars.size(); i++) {
concatenatedStarNames += stars.get(i).getName();
if (i < stars.size() - 1) concatenatedStarNames += ", ";
}
And then you set the text of the text view to concatenatedStarNames.
You can build it yourself with a StringBuilder, something like:
final Collection<Star> stars = models.get(position).getStars();
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (Star star : stars) {
final String name = star.getName();
if(first) {
first = false;
builder.append(name);
} else {
builder.append(", ").append(name);
}
}
final String allStarNames = builder.toString();
you can just do - (with your same logic of accessing stars)
String strNames;
for (int i=0; i<starsCount; i++){ //starsCount = No of stars in your JSON
strNames += model.get(position).getStars().get(i).getName();
if( i != starsCount-1)
strNames += ", ";
}
textViewVariable.setText(strNames);
I have a code here that changes the color of a word from a sentence. Violet if the word found is of the same position. Yellow if the answer contains a word but of a different position and red if the word is not found.
My problem right now is that the color changes to violet even though the word is of different position. I also tried to use splitInput[i].contains(splitAnswer[i]) to change the word to yellow but i got a repeated words for example "It was a a sample sample sentence sentence".
String answer = "This is a sample sentence"
String userInput = "It was a sample sentence"
boolean wordFound = false;
String[] splitAnswer = answer.split(" ");
String[] splitInput = userInput.split(" ");
for (int i=0; i<splitAnswer.length;i++)
{
for (int j=0;j<splitInput.length;j++)
{
if(splitInput[i].equalsIgnoreCase(splitAnswer[i]))
{
wordFound = true;
//color the word to violet
}
{
if(wordFound==false)
{
//color the word to red
}
//display the sentence
wordFound == false;
}
String answer = "This is a sample sentence";
String userInput = "It was a sample sentence";
boolean wordFound = false;
String[] splitAnswer = answer.split(" ");
String[] splitInput = userInput.split(" ");
for (int i=0; i<splitAnswer.length;i++)
{
if (splitInput[i].equalsIgnoreCase(splitAnswer[i]))
{
System.out.println ("Word found");
}
else if(!wordFound)
{
System.out.println ("Word Not found");
}
}
I'm parsing a json file with this code:
JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));
This is the json file :
{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}
I would like to display just the "London" in the name section not the Number.
I found this Code Snippet but I don't know how to use it :
case spots:
number = pSpotsJSON.optString("id");
name = pSpotsJSON.optString("name");
address = pSpotsJSON.optString("description");
status = pSpotsJSON.optString("status");
displayName = buildDisplayName(name);
break;
default:
throw new IllegalArgumentException("Cannot parse spots from JSON: unknown provider " + provider.getName());
}
}
private String buildDisplayName(String name) {
String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(name);
if (m.find()) {
return m.group();
}
return name;
}
Any help would be great!
What about getting a substring after the "-" of your String?
Would give something like this:
String contractName = stationJson.getString("contract_name");
contractName = contractName.substring(contractName.indexOf("-")+2); //+2 for the minus + space caracters