2012-04-24 17 views
0

我有一個非常簡單的消息傳遞應用程序設置。我只需從EditText框中獲取文本,並將其作爲參數傳遞給將其添加到我的數據庫的php頁面。它適用於一個單詞條目。我在EditText框中輸入空格的那一刻不起作用。我在Android上還很新。我真的不明白這是怎麼發生的。有人知道這會發生嗎?發送EditText.getText()到服務器。只適用於單個單詞。怎麼樣?

這裏是我的onClick方法:

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

       } 

    } 

我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"; 

     } 

     } 

我應該如何去解決這個問題呢?

回答

2

你必須編碼你的消息,使其「URL安全」。空格(和其他特殊字符)不能出現在URL中;這就是爲什麼如果你在瀏覽器地址欄中輸入空格,你的瀏覽器會替換%20。嘗試在function.sendMessage()如下:

URI website = new URI("http://abc.com/user_send.php?username="+username+"&where="+where+"&message="+URLEncoder.encode(string, "UTF-8")); 

通知在年底使用URLEncoder

+0

哦!這很有道理。我不敢相信我沒有想到這一點。 – EGHDK 2012-04-24 22:30:59

+0

我在URLEncode下得到一條紅線。 「方法URLEncoder(字符串,字符串)未定義類型函數」 – EGHDK 2012-04-24 22:43:48

+0

哦,哎呀!我忘了包括這個方法。它應該是'URLEncoder.encode(字符串,「UTF-8」)'。我也會更新上面的答案。對於那個很抱歉! – Rain 2012-04-24 22:46:17

相關問題