I am using Yandex.Translate API to translate a String. It does so successfully as seen in the logcat. But when I set the EditText value (eText) to the translation result, it doesn't parse the data correctly and it shows something like {"code":200,"lang":"en-ru","text":["Он не работает!"]}, the second result instead of the first required result which is "Он не работает!"
2019-06-11 02:36:57.917 14680-
14731/com.bahraindiction.goldeneagle.sightling D/Translation Result:: Он
не работает!
2019-06-11 02:36:57.918
1468014680/com.bahraindiction.goldeneagle.sightling D/Translation Result:
{"code":200,"lang":"en-ru","text":["Он не работает!"]}
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
String translationResult = null; // Returns the translated text as a String
try {
translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Translation Result",translationResult); // Logs the result in Android Monitor
eText.setText(translationResult);
}
As seen above, Log.d displays the translated result correctly AND displays the "unparsed" translation, while eText only displays the unparsed result only.
translationResult is in JSON format, Please parse that JSON first and pick the text string and set to eText. You can use gson or similar library to parse JSON.
Related
I'm writing an Android app that connects to a SOAP webservice using kSOAP2, and I have a kXML element where I would like to inject a child based on an XML string I got from elsewhere (a REST API). I have the following code:
Element samlHeader = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
samlHeader.setPrefix("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
samlHeader.setPrefix("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
String samlTokenString = ...; //I got this from elsewhere
Element samlTokenElement = ...; //I don't know how to build this
samlHeader.addChild(Node.ELEMENT, samlTokenElement);
So I'm trying to figure out how to build my Element based on the XML string I'm getting from elsewhere.
This is the solution that we ended up implementing:
try {
KXmlParser parser = new KXmlParser();
parser.setInput(new StringReader(samlTokenString));
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
Document samlTokenDocument = new Document();
samlTokenDocument.parse(parser);
samlHeader.addChild(Node.ELEMENT, samlTokenDocument.getRootElement());
} catch (XmlPullParserException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
} catch (IOException e) {
Log.e(TAG,"Could not parse SAML assertion", e);
}
We're still validating if it produces the right result but it seems to work.
I'm stuck at trying to get a simple string from a JsonObject.
Here is the basic code. result is a JsonObject returned from an Asynctask. I've done dozens of the same way, and here it doesn't work.
Response:{"status":200}
Error: An error is thrown saying "No value for 1"
When I Log the content of the JsonObject, I get this: 200, which is what I want. For which reason could this return null when there is a value?
Edit if I use the result.has("status"); true is returned. I don't understand.
Log.e("TAG", result.get("status").toString());
try{
String status = result.getString("status");
} catch (Exception e){
e.getMessage();
}
You are getting int value in the object and you are holding in string which causes the error
You are getting int value in status
{
"status":200
}
if it is like
{
"status":"200"
}
Your code works perfectly.
Try this
Log.e("TAG", result.get("status").toString());
try{
int status = result.getInt("status");
} catch (Exception e){
e.getMessage();
}
So, I am trying to retrieve JSON data from a webservice. It usually works. It doesn't work, however, if the value of a certain variable has double quotations as part of its content. For example, if I am parsing this data:
{"ID":"1057","PlaceTitle":"Place 1","PlaceDetails":"George Bush once said "This is the best dang place in the world""}
I get an error on "George bush... because it is trying to detect it as a variable because of the quotes, I believe. This exception is thrown:
org.json.JSONException: Unterminated object at character 1418 of
So what I want to do is "if this exception is thrown, treat it as content within PlaceDetails, and continue on." Any idea how I can accomplish this?
Code:
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
try {
arrayOfLocationss.add(new Location(context,
json.getInt("ID") json
.getString("PlaceTitle"), json
.getString("PlaceDetails"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
You need to fix the webservice so it returns properly formatted JSON. Quotes inside of strings need to be escaped with a backslash:
{"ID":"1057","PlaceTitle":"Place 1","PlaceDetails":"George Bush once said \"This is the best dang place in the world\""}
Why dont you escape all double quotes when you use getString? Try something like
arrayOfLocationss.add(new Location(context,
json.getInt("ID") json
.getString("PlaceTitle").toString().replaceAll("\"", "\\\""),
json.getString("PlaceDetails").toString().replaceAll("\"", "\\\""));
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)
Here is the code so far I am trying but it is showing me error:
URL url = null;
try {
url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1");
Document doc = null;
try {
System.out.println("2");
doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3");
Element table = doc.select("table[title=Avgångar:]").first();
System.out.println("4");
Iterator<Element> it = table.select("td").iterator();
//we know the third td element is where we wanna start so we call .next twice
it.next();
it.next();
while(it.hasNext()){
// do what ever you want with the td element here
System.out.println(it.next());
//iterate three times to get to the next td you want. checking after the first
// one to make sure
// we're not at the end of the table.
it.next();
if(!it.hasNext()){
break;
}
it.next();
it.next();
}
It prints System.out.println("3");
then it stops in this line
Element table = doc.select("table[title=Avgångar:]").first();
How can i solve this problem,
Thanks
It looks like the website you're trying to parse the HTML from has an error and doesn't have any tables on it. This is what's causing the null pointer exception. doc.select("table[title=Avgångar:]") isn't returning an element and then you're trying to call a method on it. To prevent this error from happening again, you could do something like this:
Elements foundTables = doc.select("table[title=Avgångar:]");
Element table = null;
if(!foundTables.isEmpty()){
table = tables.first();
}
Now, if any table was found, the table variable won't be null. You'll just have to alter the code to adapt in case no tables are found.
You're not checking the result of doc.select() before calling .first(). If there are no elements in the document that match the specified query, doc.select() could return null. Then you are calling .first() on a null pointer which, of course, will throw an exception. There is no table tag with the title you have specified in the document that you are using in your example. So, the result is not surprising.