2014-07-02 56 views
0

如何在Android中將php echo讀入字符串?如何在Android中將php echo讀入字符串?

我想獲得成功或失敗的回聲響應。

如果用戶登錄到頁面,如果用戶名稱在數據庫中不匹配,則不應允許用戶登錄並顯示某些失敗消息。

MainActivity類別

public class MainActivity extends Activity implements OnClickListener { 

    EditText name,number; 
    Button login; 
    SetContact contact; 

    Boolean isInternetPresent = false; 
    ConnectionDetector cd; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.contact); 

     cd = new ConnectionDetector(getApplicationContext()); 


     name = (EditText) findViewById(R.id.etname); 
     number = (EditText) findViewById(R.id.etnumber); 

     login = (Button) findViewById(R.id.login); 
     login.setOnClickListener(this); 
    } 

    public static String POST(String url, SetContact contact){ 
     InputStream inputStream = null; 
     String result = ""; 
     try { 


      HttpClient httpclient = new DefaultHttpClient(); 

      HttpPost httpPost = new HttpPost(url); 

      String json = ""; 

      JSONObject jsonObject = new JSONObject(); 
      jsonObject.accumulate("name", contact.getName()); 
      jsonObject.accumulate("number", contact.getNumber()); 



      json = jsonObject.toString(); 

      StringEntity se = new StringEntity(json); 

      httpPost.setEntity(se); 

      httpPost.setHeader("Accept", "application/json"); 
      httpPost.setHeader("Content-type", "application/json"); 

      HttpResponse httpResponse = httpclient.execute(httpPost); 

      inputStream = httpResponse.getEntity().getContent(); 

      if(inputStream != null) 
       result = convertInputStreamToString(inputStream); 
      else 
       result = "Did not work!"; 

     } catch (Exception e) { 
      Log.d("InputStream", e.getLocalizedMessage()); 
     } 

     return result; 
    } 

    public void onClick(View view) { 

     String username = name.getText().toString(); 
     String password = number.getText().toString(); 
     /* if(username.equals("name") && password.equals("number")){ 


       Toast.makeText(getBaseContext(), "Username and password incorrect", Toast.LENGTH_LONG).show(); 
      } */  

    /*else { 

      Toast.makeText(getBaseContext(), "Username does not exist. Please register.", Toast.LENGTH_LONG).show(); 
     }   */ 




     switch(view.getId()){ 
      case R.id.login: 
       if(!validate()) { 
        Toast.makeText(getBaseContext(), "Please Enter Valid data!", Toast.LENGTH_LONG).show(); 
       } else { 

       new HttpAsyncTask().execute("myurl?name="+username+"&number="+password); 
       } 
      break; 
     } 

    } 
    private class HttpAsyncTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

      contact = new SetContact(); 
      contact.setName(name.getText().toString()); 
      contact.setNumber(number.getText().toString()); 


      return POST(urls[0],contact); 
     } 


     protected void onPostExecute(String result) { 

      isInternetPresent = cd.isConnectingToInternet(); 

      if (isInternetPresent) { 
       Toast.makeText(getBaseContext(), "Thanks for the Mail, We will Reply you soon", Toast.LENGTH_LONG).show(); 
       name.setText(""); 
       number.setText(""); 

       Intent in = new Intent(getApplicationContext(), Updates.class); 
       startActivity(in); 
      } else { 

       showAlertDialog(MainActivity.this, "No Internet Connection", "Please Connect Internet.", false); 
      }     
     } 
    } 


    private boolean validate(){ 




      if(name.length() > 25){ 
      Toast.makeText(getApplicationContext(), "pls enter less the 25 characher in user name", Toast.LENGTH_SHORT).show(); 


      return true; 
     } 

     else if(name.length() == 0 || number.length() == 0){ 
      Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show(); 
      return false; 
     } 

     else if(number.length() < 6 || number.length() > 13){ 

      number.setError("Not Valid Phone Number"); 
      return false; 

     } 
      return true; 



    } 
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 
     while((line = bufferedReader.readLine()) != null) 
      result += line; 

     inputStream.close(); 
     return result; 

    } 

    @SuppressWarnings("deprecation") 
    public void showAlertDialog(Context context, String title, String message, Boolean status) { 
     AlertDialog alertDialog = new AlertDialog.Builder(context).create(); 


     alertDialog.setTitle(title); 

     alertDialog.setMessage(message); 

     alertDialog.setIcon((status) ? R.drawable.fail : R.drawable.fail); 

     alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
      } 
     }); 

     alertDialog.show(); 
    } 

} 
+0

你提的問題是非常普遍的,請解釋一下,你是如何進行的HTTP請求以及如何使用/運行PHP的網站。 – alex

回答

0

試試這個

HttpResponse response = client.execute(httpPost); 

String responseBody = EntityUtils.toString(response.getEntity()); 

提示:我在PHP中使用打印,而不是附和

+0

它不起作用 – user3313444

+0

您是否嘗試過打印?它對我工作很好,並在打印中傳遞json值 – APriya

+0

我用打印替換並檢查了它,但它顯示了感謝消息,它顯示welcome.even,但對於無效用戶,它也正在登錄 – user3313444

0

你提的問題是非常普遍的,所以我的答案是,太。您可以在PHP生成輸出,例如通過echo像「登錄失敗」,並在Android方評估它。更好的是,登錄後(PHP side/Android side),您可以使用HTTP狀態碼來暗示成功或失敗(如未經授權/ 401)。

由於您沒有代碼,實際上通過GET請求登錄,因此您應該閱讀如何操作this

+0

你可以請編輯我的代碼更新它 – user3313444

+0

我可以指導你編寫代碼,但我想做你的完整工作。因此,請只發布代碼草稿,例如基於我的帖子中的鏈接,我們可以一起解決......我的文章中的最後一個鏈接幾乎解決了您在Android端的問題 – alex

0

你應該使用JSON而不是字符串。

我使用JsonSimple庫將其解析爲對象。

這裏是我的代碼有一個例子:

HashMap<String, String> urlParams = new HashMap<String, String>(); 
    urlParams.put("KEY", Value); 
    String result = "-1"; 
    try { 
     result = rest.POST(host, "Response.php", this.header, 
       urlParams, 3000); 
    } catch (URISyntaxException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    JSONObject json = new JSONObject(); 
    try { 
     json = (JSONObject) new JSONParser().parse(result); 
     return json.get("value_you_want").toString(); 
    } catch (ParseException e) { 
     return ("Error parsing " + e.getMessage()); 

    } 
相關問題