2012-10-18 72 views
1

我是一個初學者在android.I已經建立了一個應用程序登錄leave模塊。爲了通過PHP連接它與mySql ..我嘗試了這個代碼從一個網站。Android通過Java的PHP連接

package com.example.axdroid; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Axdroid extends Activity { 
Button b; 
EditText et,pass; 
TextView tv; 
HttpPost httppost; 
StringBuffer buffer; 
HttpResponse response; 
HttpClient httpclient; 
List<NameValuePair> nameValuePairs; 
ProgressDialog dialog = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_axdroid); 

    b = (Button)findViewById(R.id.Button01); 
    et = (EditText)findViewById(R.id.username); 
    pass= (EditText)findViewById(R.id.password); 
    tv = (TextView)findViewById(R.id.tv); 

    b.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      dialog = ProgressDialog.show(Axdroid.this, "", 
        "Validating user...", true); 
      Intent i=new Intent(getApplicationContext(),Userpage.class); 
      startActivity(i);     
      new Thread(new Runnable() { 
        public void run() { 
         login();       
        } 
        }).start();   

     } 
     });} 
void login(){ 
    try{   

     httpclient=new DefaultHttpClient(); 
     httppost= new HttpPost("http://192.168.1.222/AndroidLeave/check.php"); 
     //add your data 
     nameValuePairs = new ArrayList<NameValuePair>(2); 
     // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
     nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value']; 
     nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     //Execute HTTP Post Request 
     response=httpclient.execute(httppost); 
     // edited by James from coderzheaven.. from here.... 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
     final String response = httpclient.execute(httppost, responseHandler); 
     System.out.println("Response : " + response); 
     runOnUiThread(new Runnable() { 
      public void run() { 
       tv.setText("Response from PHP : " + response); 
       dialog.dismiss(); 
      } 
     }); 

     if(response.equalsIgnoreCase("User Found")){ 
      runOnUiThread(new Runnable() { 
       public void run() { 
        Toast.makeText(Axdroid.this,"Login Success", Toast.LENGTH_SHORT).show(); 
       } 
      }); 

      startActivity(new Intent(getApplicationContext(), Userpage.class)); 
     }else{ 
      showAlert();    
     } 

    }catch(Exception e){ 
     dialog.dismiss(); 
     System.out.println("Exception : " + e.getMessage()); 
    } 
} 
public void showAlert(){ 
    Axdroid.this.runOnUiThread(new Runnable() { 
     public void run() { 
      AlertDialog.Builder builder = new AlertDialog.Builder(Axdroid.this); 
      builder.setTitle("Login Error."); 
      builder.setMessage("User not Found.") 
        .setCancelable(false) 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
         } 
        });      
      AlertDialog alert = builder.create(); 
      alert.show();    
     } 
    }); 
} 

} 

我無法使這項工作在調試代碼...控制從HttpClient的跳躍趕code.Would欣賞這個排序任何幫助。

這是PHP文件。我已經單獨檢查過它,它正在工作。

<?php 
$hostname_localhost ="localhost"; 
$database_localhost ="mydatabase"; 
$username_localhost ="root"; 
$password_localhost =""; 
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) 
or 
trigger_error(mysql_error(),E_USER_ERROR); 

mysql_select_db($database_localhost, $localhost); 


$username = $_POST['username']; 
$password = $_POST['password']; 


$query_search = "select * from tbl_user where username = '".$username."' AND password = '".$password. "'"; 
$query_exec = mysql_query($query_search) or die(mysql_error()); 
$rows = mysql_num_rows($query_exec); 
//echo $rows; 
if($rows == 0) { 
echo "No Such User Found"; 
} 
else { 
echo "User Found"; 
} 
?> 

@ashwani 這是本Axdroid.java頁(主要活動頁)

public class Axdroid extends Activity { 
Button b; 
EditText et,pass; 
TextView tv; 
HttpPost httppost; 
StringBuffer buffer; 
HttpResponse response; 
HttpClient httpclient; 
List<NameValuePair> nameValuePairs; 
ProgressDialog dialog = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_axdroid); 

    b = (Button)findViewById(R.id.Button01); 
    et = (EditText)findViewById(R.id.username); 
    pass= (EditText)findViewById(R.id.password); 
    tv = (TextView)findViewById(R.id.tv); 

    b.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      String url="http://192.168.1.222/AndroidLeave/check.php"; 
      JSONParser jparser= new JSONParser(); 
      ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("tag", "getcategory")); 
      params.add(new BasicNameValuePair("username", et.getText().toString())); 
      params.add(new BasicNameValuePair("password", pass.getText().toString())); 
      JSONObject jObj= jparser.makeHttpRequest(url, "POST", params);try { 
       String success = jObj.get("success").toString(); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }    


     } 
     });}' 
+0

請把你的PHP文件也。所以,它能夠更好地發現錯誤 –

+0

這是PHP file..I已分別檢查它和它的工作。 – tanmayee

+0

是否在控制檯上打印? System.out.println(「Response:」+ response);然後打印然後打印哪個字符串? –

回答

2

用於解析我用下面的類數據

JsonParser.java

public class JSONParser { 

    InputStream is = null; 
    JSONObject jObj = null; 
    String json = ""; 

    public JSONParser() { 
    } 

    // function get json from url 
    // by making HTTP POST or GET method 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if (method == "POST") { 
       // request method is POST 
       // defaultHttpClient 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

       HttpResponse httpResponse = httpClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 

      } else if (method == "GET") { 
       // request method is GET 
       DefaultHttpClient httpClient = new DefaultHttpClient(); 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       is = httpEntity.getContent(); 
      } 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(""); 

      Log.d("reader value in json parser", reader.toString()); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       Log.d("line in JsonParser", line); 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      json = sb.toString(); 
      Log.d("Json value", json); 

     } catch (Exception e) { 
      Log.d("Buffer Error", "Error converting result " + e.toString()); 
     } 

     // try parse the string to a JSON object 
     try { 

      jObj = new JSONObject(json); 
      json = ""; 
     } catch (JSONException e) { 
      Log.d("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     return jObj; 
    } 
} 

現在在你的活動嘗試通過這樣的網址

String url="place your url here"; 
JSONParser jparser= new JSONParser(); 
params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("tag", "getcategory")); 
params.add(new BasicNameValuePair("username", username.getText().toString())); 
params.add(new BasicNameValuePair("password", password.getText().toString())); 
JSONObject jobj= jparser.makeHttpRequest(url, "POST", params); 

//現在這裏從JSON檢索數據:

String success= jobj.get("success"); 

希望這有助於!

也在你的php文件中你必須使用json_encode功能之前echo

+0

謝謝@Ashwani ...我有幾個問題,很抱歉無知,因爲這是新的1)JsonParser類應該被添加到src文件分開在android文件中的權利? 2)定義的類在activity.java頁面中調用?我會嘗試你的解決方案並回來。謝謝 – tanmayee

+0

Ans 1)。是在src文件夾中創建一個名爲JSONParser的單獨類。 Ans 2)在您的問題中調用axdroid.java中的makeHttpRequest函數 – Ashwani

+0

謝謝。我會嘗試發佈進度。這個jobj.get中的 – tanmayee

0

使用此功能。根據您的要求進行更改。

void login() 
     { 
      String data = null; 
      InputStream is = null; 
      StringBuilder sb; 
      String result; 

      try 
      { 
       HttpClient httpsClient = new DefaultHttpClient(); 
       HttpPost httpPost = new HttpPost("http://192.168.1.4/check.php"); 
       List<NameValuePair> nameValue = new ArrayList<NameValuePair>(); 

       nameValue.add(new BasicNameValuePair("username", "" + et.getText().toString())); 
       nameValue.add(new BasicNameValuePair("password", "" + pass.getText().toString())); 


       httpPost.setEntity(new UrlEncodedFormEntity(nameValue)); 


       HttpResponse httpRes = httpsClient.execute(httpPost); 


       HttpResponse httpResponce = httpsClient.execute(httpPost); 
       HttpEntity httpEntity = httpResponce.getEntity(); 
       is = httpEntity.getContent(); 

      } 
      catch(Exception e) {} 


      try 
       { 
        BufferedReader BufR = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8); 
        sb = new StringBuilder(); 
        sb.append(BufR.readLine() + "\n"); 
        String line = "0"; 

        while((line = BufR.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 


        result = sb.toString(); 

        Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show(); 
        if(result.equals("User Found")) 
        { 
         Toast.makeText(getApplicationContext(), "User Found ", Toast.LENGTH_LONG).show(); 
        } 
        else 
        { 
         Toast.makeText(getApplicationContext(), "User Not Found ", Toast.LENGTH_LONG).show(); 
        } 
       } 
       catch (Exception e) { 
        Log.e("log_tag", "Error in convert String" + e.toString()); 
       } 





     } 
+0

。我試過這段代碼...控件從「is」跳到「Log.e」,我開始報錯。 – tanmayee

+0

你改變路徑,並給予互聯網許可。 –

+0

是的...我做到了 – tanmayee