2

I am looking for a solution to add inside a String URL a variable (Post parameter).

SharedPreferences sp = getPreferences(MODE_PRIVATE);    
String my_variable = "test";
private  static final String READ_COMMENTS_URL = "http://xxx/comments.php?usernames= my_variable";  

It should eventually possible with string.format. Can anyone give a hint?

5
  • Post parameters don't come in url itsef. Commented Jan 16, 2015 at 16:37
  • what you want exactly to do ? why you dnt use smth like String READ_COMMENTS_URL = "xxx/comments.php?usernames="+ my_variable; Commented Jan 16, 2015 at 16:38
  • i have tried this before but then allways the android app crash after login Commented Jan 16, 2015 at 16:55
  • i wanted load a username of sharedpreferences and add this add end of the url to make a query over php /mysql Commented Jan 16, 2015 at 16:56
  • Do what @MariaGheorghe suggested. That's how its done. If your app is crashing then issue must be something else. Put your logcat error trace. Commented Jan 16, 2015 at 16:58

4 Answers 4

4
SharedPreferences sp = getPreferences(MODE_PRIVATE);    
String my_variable = "test";
private  static final String READ_COMMENTS_URL = "http://xxx/comments.php?usernames= "+my_variable;
Sign up to request clarification or add additional context in comments.

Comments

3

I would use Java String formatting like below:

SharedPreferences sp = getPreferences(MODE_PRIVATE);    
String my_variable = "test";
private static final String READ_COMMENTS_URL = 
    String.format("http://xxx/comments.php?usernames=%s", my_variable);

Here is reference for Formatting Strings: http://alvinalexander.com/blog/post/java/use-string-format-java-string-output

Comments

2

In your code my_variable is a string not variable because you using it as string inside of double quotes("")

 private  static final String READ_COMMENTS_URL =
 "http://xxx/comments.php?usernames= my_variable";

If you are using variable with string you have to concatenate string with variable

private  static final String READ_COMMENTS_URL =
     "http://xxx/comments.php?usernames="+my_variable;

If you want to format your string use String class api

static String format(String format, Object... args)
Formats the supplied objects using the specified message format pattern.

private static final String READ_COMMENTS_URL = 
    String.format("http://xxx/comments.php?usernames=%s", my_variable);

Comments

0

java.text.MessageFormat should work for you - http://developer.android.com/reference/java/text/MessageFormat.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.