как передать параметр из одной активности на сторону php и получить другую активность? в php, я буду делать запрос, поэтому мой запрос зависит от переданного параметра от одного действия, а другое действие покажет результат этого запроса. спасибо за помощь.
1> как передать параметр приложения android на сайт php. 1> создать один JS-парсер 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> создайте один класс пользовательской функции для параметра pass или получателя на php UserFunctions.java. в этом классе одна функция для получения данных с сайта 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 при нажатии кнопки входа. loginActivity.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(); } }
}