This has to be a really easy answer. I've been searching and searching on how to compare a variable to a string in Java. I have an Intent and only want to declare some vars if data from the intent matches. Surely this can't be that hard. Java is frustrating to me. :)
I know that type will equal message at some point but it doesn't work.
e.g.
String type = intent.getStringExtra("type");
if(type.equals("message")){
String msg = intent.getStringExtra("message");
String avatar = intent.getStringExtra("photo");
count = Integer.parseInt(intent.getStringExtra("count"));
Bitmap photo = getBitmapFromURL(avatar);
String theMessage = Html.fromHtml(msg).toString().replace("\\", "");
}
EDIT:
I did output type to log as suggested and it does show message like it should. I am trying to us the same variable theMessage and photo but it complains that its not declared so it prompts a fix and puts this at the top. Is this what's causing it not to work? This is a notification by the way.
private static String theMessage = null;
private static Bitmap photo = null;
I try to do this later in the code but it complains about not being declared.
if(type.equals("message")){
notification.setSubText(theMessage);
notification.setLargeIcon(photo);
}
So that is what I have and with the static vars it doesn't work at all even after the error of not being declared goes away.
Try instead
Bundle extras = intent.getExtras();
String type = extras.getString("type");
Log.i("type", type);
if(type.equals("message")){
String msg = extras.getString("message");
String avatar = extras.getString("photo");
count = Integer.parseInt(extras.getString("count"));
Bitmap photo = getBitmapFromURL(avatar);
String theMessage = Html.fromHtml(msg).toString().replace("\\", "");
}
and see the logCat what comes against type.
Hope it helps.
Related
I have some URLs' in string form, and from these URLs' I want to generate a URI using java.net.URI.
These URLs' are actually hyperlinks in an Android Webview:
clc://C# or clc://C++
final URI u = new URI(newURL);
final String sScheme = u.getScheme();
final String sHost = u.getHost();
final String sPath = u.getPath();
But in the above code, if a URL has # or + then getHost() returns null.
I tried to encode the URL as follows, but it doesn't work:
String encodedUrl = URLEncoder.encode(url, "UTF-8");
I also tried putting %23 for #, then too it doesn`t work.
Please help me to resolve this.....
URLEncoder doesn't always provide the correct output, especially when URIs' are involved.
Try the following approach instead:
Uri u = Uri.parse(newURL)
.buildUpon()
.appendQueryParameter("param", param)
.build();
String url = u.toString();
where param is a web service parameter (if using any). This will encode the URL in UTF-8 format correctly. Then,
final String sScheme = u.getScheme( );
final String sHost = u.getHost( );
final String sPath = u.getPath( );
It will work as expected.
Before you judge me, I'd like to say I read theese:
Saving a List of Strings in Android with SharedPreferences
Misbehavior when trying to store a string set using SharedPreferences
getString(String key, String defValue) - Reference
But I still can't understand, can't get things work. I get totally misbehavior of my preferences. My code:
public static SharedPreferences sharedAppPreferences;
public static final String AppsListKey = "AppListKey";
public static final String AppsPreferences = "AppsPreferences";
public static ArrayList<String> packageNames;
public void chooseApps(View view) {
sharedAppPreferences = getSharedPreferences(AppsPreferences, Context.MODE_PRIVATE);
if (sharedAppPreferences.contains(AppsListKey)) {
Set<String> buffer = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));
packageNames = new ArrayList<String>(buffer);
} else {
packageNames = new ArrayList<String>();
}
PackageManager packageManager = getPackageManager();
int flags = PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES | PackageManager.GET_UNINSTALLED_PACKAGES;
List<ApplicationInfo> packageList = packageManager.getInstalledApplications(flags);
for (ApplicationInfo pack : packageList) {
if (((pack.flags & ApplicationInfo.FLAG_SYSTEM) == 1) || packageNames.contains(pack.loadLabel(packageManager).toString())) {
// System application or already in array
} else {
// Installed by user and isnt in array
packageNames.add(pack.loadLabel(packageManager).toString());
}
}
Editor editor = sharedAppPreferences.edit();
Set<String> buffer1 = new LinkedHashSet<String> (packageNames);
editor.putStringSet(AppsListKey, buffer1);
editor.commit();
//packageNames.clear();
//buffer1.clear();
buffer1 = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));
packageNames = new ArrayList<String>(buffer1);
AppList appList = new AppList();
appList.show(getSupportFragmentManager(), "AppList");
}
Why first time I run my app I get list like
[Skype, Facebook, Whatsapp, Twitter, Google+]
It's ok as long as app is running... But if I kill my app and restart I get now totally different list like
[Whatsapp, Google+, Skype, Twitter, Facebook]
Could someone explain me please what is here wrong?
The only difference in your list before and after, is the ordering...
To expand on what I have been talking about, I just realised your mistake..
LinkedHashSet is ordered. However, you are storing in
Set<String> buffer
Set<String> is not ordered...
So it jumbles it up again.
You need to store it in parameter of LinkedHashSet like below
LinkedHashSet<String> buffer = new LinkedHashSet<String>(sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>()));
(There are two occasions i see this needs to be changed. )
Edit:
One final thing you can do to help, is rather than create a new list, cast the existing one from shared prefs ...
LinkedHashSet<String> buffer = (LinkedHashSet<String>)sharedAppPreferences.getStringSet(AppsListKey, new LinkedHashSet<String>());
There are alternatives to HashSets here
I need to do to a String manipulation. Initially I will be getting an image path as one of the below:
image = images/registration/student.gif
image = images/registration/student_selected.gif
image = images/registration/student_highlighted.gif
and I need to manipulate the string image path to get 2 different image paths.
One is to get the path as:
image1 = images/registration/student.gif
for that I used the function below:
private String getImage1(final String image) {
String image1 = image;
image1 = image.replace("_highlight", "");
image1 = image.replace("_selected", "");
return image1;
}
the second image path I need is to get the path:
image2 = image = images/registration/student_selected.gif
the function I used to get the image2 output was:
private String getImage2(final String image) {
String image2 = image;
boolean hasUndersore = image2.matches("_");
if (hasUndersore) {
image2 = image2.replace("highlight", "selected");
} else {
String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
return image2;
}
But the above methods didn't give me the expected result. Can anyone help me with it?
Thanks a lot!
you could use indexOf(...) instead of match(). match will check the whole string against the regex.
for (final String image : new String[] { "images/registration/student.gif", "images/registration/student_highlight.gif",
"images/registration/student_selected.gif" }) {
String image2 = image;
final boolean hasUndersore = image2.indexOf("_") > 0;
if (hasUndersore) {
image2 = image2.replaceAll("_highlight(\\.[^\\.]+)$", "_selected$1");
} else {
final String[] words = image2.split("\\.");
image2 = words[0].concat("_selected.") + words[1];
}
System.out.println(image2);
}
this will give you expected output.
btw, i changed replaceAll(..) regex, since the image filename could have string "highlight" as well. e.g. stuhighlight_highlight.jpg
If I understood correctly, you need below outputs from respective functions
"images/registration/student.gif"-> getImage1(String)
"images/registration/student_selected.gif" -> getImage2(String)
Assuming above output, there are few mistakes in the both functions
getImage1()->
In the second replace you need to use image1 variable which is output of first replace.
You need to replace "_highlighted" and not "_highlight"
getImage2()->
If you need to search for '_' then use indexOf function.
You need to replace 'highlighted' not 'highlight'
I have modified the functions as below which gives required output
private static String getImage1(final String image) {
return image.replace("_highlighted", "").replace("_selected", "");
}
private static String getImage2(final String image) {
if (image.indexOf("_")!=-1) {
return image.replace("highlighted", "selected");
} else {
return image.replace(".", "_selected.");
}
}
First, getImage1() is probably not doing what you want it to do. You are assigning a value to the variable image1 3 times. Obviously the last assigned value gets returned.
Second, image2.matches("_") will not tell you if image2 contains an underscore (which I think is what you're trying to do here).
I suggest to do some more testing/debugging yourself first.
1.
private String getImage1(final String image) {
return image.replaceAll("_(highlighted|selected)", "");
}
2.
private String getImage2(final String image) {
return image.replaceAll(getImage1(image).replaceAll("(?=.gif)", "_selected");
}
b = this.getIntent().getExtras();
s = this.getIntent().getStringExtra("DEFAULTTEXT");
public void onClick(View v)
{
String a = "http://152.226.152.156:1010/jsp-examples/test1";
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(a);
httpurlconnection = (HttpURLConnection) url
.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setRequestMethod("POST");
Toast.makeText(Booking.this, a, Toast.LENGTH_SHORT).show();
Toast.makeText(Booking.this, "Toast1", Toast.LENGTH_SHORT).show();
ObjectOutputStream dos = new ObjectOutputStream(httpurlconnection.getOutputStream());
SendVEctor.add(txtArrivalTime.getText().toString());
SendVEctor.add(txtFerry.getText().toString());
SendVEctor.add(txtStatus.getText().toString());
SendVEctor.add(txtDestination.getText().toString());
SendVEctor.add(s.toString());
dos.writeObject(SendVEctor);
dos.close();
s would be my intent and how would i put it into my SendVEctor?
Thank you.
I do not know what Intent is. But you can do something like this,
Vector<Intent> sendVector = new Vector<Intent>();
sendVector.add(this.getIntent());
I assume SendVEctor is a type of Vector, so it would be perfectly legal to add objects to it. It would be better if you can throw some more light on the question.
SendVEctor sVector = new SendVEctor();
sVector.add(this.getIntent())
s is not your intent, s is the value of the DEFAULTTEXT attribute of your actual intent. From the question, it's really hard to tell what you want to achieve.
The actual code adds this value to the vector. Because all things you add to the vector are String, I assume the vector is declared and constructed like this:
Vector<String> SendVEctor = new Vector<String>();
In this case you won't be able to add the intent object to the vector, because this vector can hold nothing but Strings.
If the vector is untyped, in other words, declared and constructed like this:
Vector SendVEctor = new Vector();
then you'll be able to add the intent with the expression
SendVEctor.add(this.getIntent());
but: Intent is not serializable so you won't be able to write the vector to the ObjectOutputStream.
Please add some more details and explain what you really want to serialize. Just text or text mixed with objects.
I am developing a Web application in Java. In that application, I have created webservices in Java. In that webservice, I have created one webmethod which returns the image list in base64 format. The return type of the method is Vector. In webservice tester I can see the SOAP response as xsi:type="xs:base64Binary". Then I called this webmethod in my application. I used the following code:
SBTSWebService webService = null;
List imageArray = null;
List imageList = null;
webService = new SBTSWebService();
imageArray = webService.getSBTSWebPort().getAddvertisementImage();
Iterator itr = imageArray.iterator();
while(itr.hasNext())
{
String img = (String)itr.next();
byte[] bytearray = Base64.decode(img);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
imageList.add(imag);
}
In this code I am receiving the error:
java.lang.ClassCastException: [B
cannot be cast to java.lang.String" on
line String img = (String)itr.next();
Is there any mistake in my code? Or is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?
Note:- I already droped this question and I got the suggetion to try the following code
Object next = iter.next();
System.out.println(next.getClass())
I tried this code and got the output as byte[] from webservice. but I am not able to convert this byte array to actual image.
is there any other way to bring the image in actual format? Can you provide me the code or link through which I can resolve the above issue?
You can check this link which provides information about converting image to Byte[] and Byte[] back to image. Hope this helps you.
http://www.programcreek.com/2009/02/java-convert-image-to-byte-array-convert-byte-array-to-image/
To convert use Base64.decode;
String base64String = (String)itr.next();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(bytearray);
I'm not familiar with what you're trying to do, but I can say this: String does have a constructor that takes a byte[].
If I understood you correctly, you tried to do String s = (String) byteArray;, which of course doesn't work. You can try String s = new String(byteArray);.
Looking at the actual error message:
java.lang.ClassCastException: [B cannot be cast to java.lang.String
on line String img = (String)itr.next();
I'm saying that perhaps you meant to do:
String img = new String(itr.next());