Pattern p = Pattern.compile(".*\\\"(.*)\\\".*");
Matcher m = p.matcher("\"Hi there\"! How are you");
if (m.find()) {
try {
String iGotMyMatchedString = m.group(0);
} catch (Exception e) {
e.printStackTrace();
}
}
Above code will return me string inside double quotes which is "Hi there".
How can i get the remaininig string "!How are you"
You can not get the unmatched string, instead you can use a capture group around the second part and access to it by calling the group(2) on your matched object:
".*\\\"(.*)\\\"(.*)"
Related
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 ;)
I have an equation which result is displayed in a TextView.
Then i have another TextView which act like a History. This History i want to save with a file and the file should be reloaded after the app will be killed an restarted.
Whats i dont understand is that the second TextView which is the View that i will save is displayed wierd stuff after starting the app
Thise line over and over again.
android.widget.TextView{41852c0 VFED.VCL ..... ID32,316-419,351 #7f09000a app:id/tvHistory}
My own Code:
final static String FILENAME = "marks.txt";
mNotenHistory=(TextView)findViewById(R.id.tVhistory);
mNotenHistory.setMovementMethod(new ScrollingMovementMethod());
private void loadTextfromFile()
{
File f = new File(getFilesDir(),FILENAME);
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
try {
while ((line = br.readLine()) != null)
{
mNotenHistory.setText(line+"\n"+mNotenHistory.getText());
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view)
{
[...]
mNotenHistory.setText(mNotenHistory.getText() + "\n" + string_note);
String noten_history_string = String.valueOf(mNotenHistory);
try {
FileOutputStream fo = openFileOutput(FILENAME, Context.MODE_APPEND);
fo.write(noten_history_string.getBytes());
fo.write("\n".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is the offending line:
String noten_history_string = String.valueOf(mNotenHistory);
Look at this definition, from the Android documentation:
public static String valueOf(Object value)
Added in API level 1
Converts the specified object to its string representation. If the object is null return the string "null", otherwise use toString() to get the string representation.
The TextView class inherits toString() from the View class. Here is its definition:
public String toString ()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression: getClass().getName() + '#' + Integer.toHexString(hashCode())
So this is your problem. String.valueOf(mNotenHistory) does not give you the text within the text view. Thus, you are writing something else (specifically, the line you mentioned) to your file. To obtain the text from your TextView, use the getText() method instead. This is what the line should look like:
String noten_history_string = mNotenHistory.getText();
Quick resume what i do want to a complish.
TextView A gets the result of an equation which is clear after each new calculation.
To save the result there is TextView B.
The Results should write from botton to top in TextView B so that the newest in on top.
The same time it should write the content of the TextView into a file.
After closing/killing the App and reopen it the TextView B will show all the saved data.
A Reset Button should clear all the content of the file so it will be empty.
I'd like an inputType in the edit text that i can input fractional number like this: 2/4 (i want print the "/").
The program is about calculating things and i need to type fractional insted of decimal. Thanks. Sorry my bad english.
I think the best way would be to use a string for your input text, then to parse the string to figure out what kind of things the user entered.
When the user has finished their input, you can check the string with something like this:
public float testInputString(String testString) {
boolean goodInput = true;
float result = 0;
if (testString.contains("/")) {
//possible division
String pieces[] = testString.split("/");
if (pieces.length != 2) {
goodInput = false;
} else {
try {
float numerator = Float.parseFloat(pieces[0]);
float denominator = Float.parseFloat(pieces[1]);
result = numerator/denominator;
} catch (Exception e) {
goodInput = false;
}
}
} else if (testString.contains(".")) {
try {
result = Float.parseFloat(testString);
} catch (Exception e) {
goodInput = false;
}
}
//TODO something here if bad input, maybe an alert or something
return result;
}
Also, you can check while they are typing for valid input if you use a keylistener like this. You could modify that to allow only numbers . and /.
put this property in xml node of Edittext and use Double notation instead of "/"
android:digits="1234567890.-"
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);
i am a new Android developer, I have a UTF-16LE encoded string. I would like to print that string in Textview of my activity. However, the string in Hindi Language. and when i get Sysout for the string it shows write format and words(Eg: 05-07 12:31:53.050: I/System.out(22887): str = बसंत पंचमी, str = मकर संक्रान्ति / पोंगल). but in the TextView of device it shows only BOXES.
here is the code:-
String myString = मकर संक्रान्ति / बसंत पंचमी;
String correct = null;
try {
byte[] utf16le = myString .getBytes("UTF-16");
correct = new String(utf16le, "UTF-16");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("str = "+correct);
Any help is appreciated.
Thanks