1

如何将参数从一个活动传递到 php 端并由另一个活动接收?在 php 方面,我会进行查询,所以我的查询取决于从一个活动传递的参数,而另一个活动将显示该查询的结果。感谢您的帮助。

4

1 回答 1

2

1> 如何将参数android app 传递给php 站点。1> 创建一个json解析器类JSONParser.java

public class JSONParser {

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        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, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

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

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);            
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

2> 在 php UserFunctions.java 上为 pass 或 receiver 参数创建一个用户函数类。在此类中,一个函数用于从 php 站点获取数据,另一个函数用于将 android 应用程序传递给 php

public class UserFunctions {

private JSONParser jsonParser;

 private static String api_URL = "http://10.0.2.2/carcab_api/";

private static String login_tag = "log_in";
private static String get_user_detail_tag = "userdetail";




// constructor
public UserFunctions() {
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * 
 * @param email
 * @param password
 * */
public JSONObject loginUser(String usr_nm, String password) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("usr_nm", usr_nm));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(api_URL, params);
    // Log.e("JSON", json.toString());
    return json;
}

/**
 * function make get User Detail  Request
 * 
 * @param email
 * @param password
 * */

public JSONObject get_user_detail(String user_id) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", get_user_detail_tag));
    params.add(new BasicNameValuePair("user_id", user_id));
    JSONObject json1 = jsonParser.getJSONFromUrl(api_URL, params);
    System.out.println(params);
    Log.e("JSON1", json1.toString());
    return json1;

}

}

3> 点击登录按钮,我将参数从 android 传递到 php。登录活动.java

public class LoginActivity extends Activity {
Button btnLogin;
EditText inputu_nm; 
EditText inputPassword;
TextView loginErrorMsg;
UserFunctions userFunction;
JSONObject json;


// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "user_id";
private static String KEY_NAME = "user_name";
private static String KEY_UNM = "user_nm";
private static String KEY_OID = "off_id";
private ProgressDialog progressDialog;

private static String KEY_CREATED_AT = "created_at";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // Importing all assets like buttons, text fields
    inputu_nm = (EditText) findViewById(R.id.u_nm);
    inputPassword = (EditText) findViewById(R.id.pass);     
    btnLogin = (Button) findViewById(R.id.btnlogin);
    loginErrorMsg = (TextView) findViewById(R.id.login_error);
    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            String u_nm = inputu_nm.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();               
            //pass user username and password to  android app to php
            JSONObject json = userFunction.loginUser(u_nm, password);

            // if json responce is success then user go to next home activity
            try {
                if (json.getString(KEY_SUCCESS) != null) {
                    loginErrorMsg.setText("");
                    String res = json.getString(KEY_SUCCESS);
                    if (Integer.parseInt(res) == 1) {   
                           Intent dashboard = new Intent(getApplicationContext(), HomeActivity.class);             
                           startActivity(dashboard);  

                    } else {
                        // Error in login
                        loginErrorMsg.setText("Incorrect Username Or Password");
                        inputu_nm.setText("");                          
                        inputPassword.setText("");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

}

}

4> 现在我从 php 获取用户详细信息到另一个活动。当用户详细信息活动启动时,然后获取 user.userdetail.java 的所有详细信息

public class userdetailActivity extends Activity {

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_SUCCESS_MSG = "success_msg";

JSONObject json_user;
UserFunctions userFunctions;
DatabaseHandler DBHandler;
String user_name = "";
String user_password = "";
String user_address = "";
String user_mobile = "";
String user_id;
TextView username, password, address, mobile;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.userdetail);
    userFunctions = new UserFunctions();
    username = (TextView) findViewById(R.id.username);
    password = (TextView) findViewById(R.id.password);
    address = (TextView) findViewById(R.id.address);
    mobile = (TextView) findViewById(R.id.mobile);
    // i am pass static value of user id now
    user_id = "1001";

    // i am pass user id and get user detail on my activity from php
    refresh_screen(user_id);

}

private void refresh_screen(String user_id) {
    JSONObject json = userFunctions.get_user_detail(user_id);
    jsonact = json;
    // check for positive response
    try {
        if (json.getString(KEY_SUCCESS) != null) {
            String res = json.getString(KEY_SUCCESS);
            if (Integer.parseInt(res) == 1) {
                json_user = json.getJSONObject("user");

                user_name = json_user.getString("username");
                user_password = json_user.getString("password");
                user_address = json_user.getString("address");
                user_mobile = json_user.getString("mobile");

                username.setText(user_name);
                password.setText(user_password);
                address.setText(user_address);
                mobile.setText(user_mobile);

            } else if (Integer.parseInt(res) == 0) {
                Toast.makeText(getApplicationContext(), "No detail Found",
                        Toast.LENGTH_LONG).show();
            }
        } else if (json.getString(KEY_ERROR) != null) {

            String res = json.getString(KEY_ERROR);
            if (Integer.parseInt(res) == 1) {
                Toast.makeText(getApplicationContext(), "No detail Found",
                        Toast.LENGTH_LONG).show();
            }

        }
    } catch (JSONException e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "No detail Found",
                Toast.LENGTH_LONG).show();

    }
}

}

于 2012-10-24T03:51:52.310 回答