Want regular expression for following? - android

I have:
<description><![CDATA[<div><b>Details:</b> <div class=ExternalClassCDAAC64F989B48B1AE79489DFBF8C27C><div><span style="font-size:8pt;font-weight:700"><font color="#008080" face=Verdana><span style="text-decoration:none"><a style="text-decoration:none" href="http://unipune.ac.in/other_academic_and_service_units/board_students_welfare/pdf/Annual_Essay_Competition_Covering_26-5-12.pdf" target="_blank"><font color="#008080">Letter Regarding Annual Essay Prize Competition</font></a></span></font></span></div></div></div>
<div><b>Expires:</b> 8/14/2012</div>
]]></description>
I need a regular expression which will give me only the href contents. I tried with this:
String link1 = a.substring(a.indexOf("href=\""), a.indexOf("\""));
But its giving me a force close error.
The output that I want is somewhat like this:
link = http://unipune.ac.in/other_academic_and_service_units/board_students_welfare/pdf/Annual_Essay_Competition_Covering_26-5-12.pdf
Can anybody help me?

try this:::: but only if this original string will be in the same format.
String[] separated = a.spilt("href=\"");
String[] first = separated[1].spilt("\" target");
String link1 = first[0];

try this
\bhref="([^"<>]+)"
Code
try {
String resultString = subjectString.replaceAll("\\bhref=\"([^\"<>]+)\"", "link=$1");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}
Test it here.
Hope this helps.

Try this.
String link1 = a.substring(a.indexOf("href=\""), a.indexOf("target=")-1);

Related

EditText is not displaying translation while Logcat does

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.

Can't get a string from nested downloaded JSON [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I'm getting a JSON from the server:
JSONObject vkjson = response.json;
I have tried to make it a string and check via LogCat to make sure it works - and yeah, it 100% works.
But it is nested:
{"response":{"first_name":"...","last_name":"..."} }
I have tried to do this:
String result = vkjson.getJSONObject("response").getString("first_name");
But IDE doesn't like the getJSONObject part and underlines it. IDE says:
Unhandled exception in org.json.JSONException
What's wrong? Is it because the JSON is loading from the server or the code is incorrect?
Thank you in advance.
Unhandled exception in org.json.JSONException
Mean that the method can throw a JSONException and you have to handle it.
So you have to:
try {
String result = vkjson.getJSONObject("response").getString("first_name");
} catch (JSONException exception){
//Handle exception here
}
There's nothing wrong with your code other than not handling the JSONException which is potentially thrown (i.e. what would happen if there isn't an object called "response").
You need to look at exception handling and wrap this code in a try .. catch block or otherwise deal with the exception.
Java exception handling
Do this-:
try
{
JSONObject vkjson = response.json;
//More code related to json
}
catch(JsonException e)
{
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(responseString);
if(jsonObject != null)
{
if (jsonObject.has("response")) {
JSONObject responseObject = jsonObject.getJSONObject("response");
String firstName = responseObject.getString("first_name");
Log.d("Tag",firstName);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Eclipse - Functions issue [duplicate]

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

Jsoup doesnt find the specified element

I'm trying to write a little android program (don't mind the messiness) that shows the last "Did you know?" from Wikipedia. But for some reason Jsoup doesn't find it.
What is the problem?
Part of the code:
Document document = null;
try {
document = Jsoup.connect("https://en.wikipedia.org/wiki/Portal:Mathematics/Did_you_know/1").get();
} catch (IOException e) {
e.printStackTrace();
}
//Document document = Jsoup.parse("test.html");
if (document != null) {
Element element = document.select("div#mw-content-text").first();
if (element == null) {
message = "empty";
} else {
message = element.html();
}
}
Part of the wikipedia source code:
<div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><p>...that outstanding mathematician Grigori Perelman was offered a Fields Medal in 2006, in part for his proof of the Poincaré conjecture, which he declined?</p>
https://en.wikipedia.org/wiki/Portal:Mathematics/Did_you_know/1
Your code works fine on a desktop. Check your android settings according to internet access rights. Also it's a good idea to check where's the real problem.
Some hints:
replace e.printStackTrace(); with a logger
write the value of message variable to a logger too
are you using an AsyncTask?
Are there any errors, exception or something similar?

Type mismatch: cannot convert from Object to JSONObject

I'm relatively new to Android development and am writing my first REST-based app. I've opted to use the Android Asynchronous HTTP Client to make things a bit easier. I'm currently just running through the main "Recommended Usage" section on that link, essentially just creating a basic static HTTP client. I'm following the code given, but changing it around to refer to a different API. Here's the code in question:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
The String venueName = firstVenue.getString("name"); line is currently throwing an error in Eclipse: "Type mismatch: cannot convert from Object to JSONObject". Why is this error occurring? I searched other threads which led me to try using getJSONObject(0) instead of get(0) but that led to further errors and Eclipse suggesting using try/catch. I haven't changed any of the code on the tutorial, save for the variable names and URL. Any thoughts/tips/advice?
Thanks so much.
EDIT:
Here is the onSuccess method, modified to include the try/catch blocks suggested. Eclipse now shows the "local variable may not have been initialized" for firstVenue here: venueName = firstVenue.getString("name"); and for venueName here: System.out.println(venueName); Even if I initialize String venueName; directly after JSONObject firstVenue; I still get the same error. Any help in resolving these would be greatly appreciated!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
You can try to convert object you are getting from querying to String and then use
final JSONObject jsonObject = new JSONObject(stringresult);
I was getting same error earlier, it worked for me.
Yes, you should be using getJSONObject to ensure that the value you obtain is a JSON object. And yes, you should catch the possible JSONException which is thrown if that index in the array doesn't exist, or does not contain an object.
It'll look something like this:
JSONObject firstVenue;
try {
firstVenue = venues.get(0);
} catch (JSONException e) {
// error handling
}
convert obj to json Object:
Object obj = JSONValue.parse(inputParam);
JSONObject jsonObject = (JSONObject) obj;
The solution provided by Shail Adi only worked for me by setting the initial values of firstVenue and venueName to null. Here's my code:
JSONObject firstVenue = null;
try {
firstVenue = (JSONObject)venues.get(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName = null;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);

Categories

Resources