I have a pretty simple set up for a messaging application. I simply get the text from an EditText box and pass it as a parameter to a php page that adds it to my database. It works perfectly for one word entries. The moment I put in a space in the EditText box it doesn’t work. I’m still fairly new at Android. I really do not understand how this could be happening. Does anyone know how this could happen?
Here is my onClick method:
public void sendMessage(View v) {
Log.d("tag", "XXXXXXXXXXXXXXXXXXXXXX");
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
username = prefs.getString("username", "null");
where = prefs.getString("chat", "null");
message = (EditText) findViewById(R.id.inptbox);
function = new Functions();
Editable messagetext;
messagetext = message.getText();
response = function.sendMessage(username, where, messagetext.toString());
String theresponse = "";
theresponse = response;
if (theresponse.compareTo("0") == 0) {
Toast.makeText(getApplicationContext(), "Success!",
Toast.LENGTH_SHORT).show();
//message.setText(null);
} else if (response.compareTo("9") == 0) {
// userent.setText("nine");
}
}
My function.sendMessage:
public String sendMessage(String username, String where, String string){
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://abc.com/user_send.php?username="+username+"&where="+where+"&message="+string);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
//add your implementation here
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l+nl);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
}
How should I go about solving this problem?
You have to encode your message to make it “URL-safe.” Spaces (and other special characters) cannot appear in URLs; this is why your browser will replace spaces with
%20if you type them into the address bar. Try the following in function.sendMessage():Notice the use of URLEncoder at the end.