我在Android Studio中创建项目(编程初学者)。该项目即将完成,但我无法解决最后一个问题。如何仅返回用户输入的数据?
在MySQL中,我有已保存的用户ID,但我不能只返回它保存到ListView的数据。存储用户ID的变量是" IDMestre"。这是我的代码:
ViewAllEmployee
public class ViewAllEmployee extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private String JSON_STRING;
Button btnAtualizar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_employee);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
btnAtualizar = (Button) findViewById(R.id.btnAtualizar);
Intent intent = getIntent();
if (intent != null) {
Bundle params = intent.getExtras();
if (params != null) {
String IDMestre = params.getString("IDMestre");
TextView txtIDMestre = (TextView) findViewById(R.id.editIDMestre);
txtIDMestre.setText(IDMestre);
}
}
btnAtualizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ViewAllEmployee.this, TelaInicial.class);
startActivity(intent);
}
});
}
private void showEmployee() {
JSONObject jsonObject = null;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String IDMesa = jo.getString(Config.TAG_IDMESA);
String Nome = jo.getString(Config.TAG_NOME);
HashMap<String, String> employees = new HashMap<>();
employees.put(Config.TAG_IDMESA, IDMesa);
employees.put(Config.TAG_NOME, Nome);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllEmployee.this, list, R.layout.list_item,
new String[]{Config.TAG_IDMESA, Config.TAG_NOME},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
private void getJSON() {
class GetJSON extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllEmployee.this, "Fetching Data", "Wait...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showEmployee();
}
@Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, ViewEmployee.class);
HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
String mesaId = map.get(Config.TAG_IDMESA).toString();
intent.putExtra(Config.TBMESA_ID, mesaId);
startActivity(intent);
}
}
&#13;
RequestHandler
public class RequestHandler {
//Method to send httpPostRequest
//This method is taking two arguments
//First argument is the URL of the script to which we will send the request
//Other is an HashMap with name value pairs containing the data to be send with the request
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
public String sendGetRequest(String requestURL){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
public String sendGetRequestParam(String requestURL, String id){
StringBuilder sb =new StringBuilder();
try {
URL url = new URL(requestURL+id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while((s=bufferedReader.readLine())!=null){
sb.append(s+"\n");
}
}catch(Exception e){
}
return sb.toString();
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
&#13;
配置
public class Config {
public static final String URL_ADD="http://mundorpg.000webhostapp.com/app_mural_mesa_edit/addMesa.php";
public static final String URL_GET_ALL = "http://mundorpg.000webhostapp.com/app_mural_mesa_edit/getAllMesa.php";
public static final String URL_GET_MESA = "http://mundorpg.000webhostapp.com/app_mural_mesa_edit/getMesa.php?id=";
public static final String URL_UPDATE_MESA = "http://mundorpg.000webhostapp.com/app_mural_mesa_edit/updateMesa.php";
public static final String URL_DELETE_MESA = "http://mundorpg.000webhostapp.com/app_mural_mesa_edit/deleteMesa.php?id=";
//Keys that will be used to send the request to php scripts
//public static final String KEY_EMP_ID = "id";
public static final String KEY_MESA_IDMESA = "IDMesa";
public static final String KEY_MESA_NOME = "Nome";
public static final String KEY_MESA_TEMATICA = "Tematica";
public static final String KEY_MESA_SISTEMA = "Sistema";
//JSON Tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_IDMESA = "IDMesa";
public static final String TAG_NOME = "Nome";
public static final String TAG_TEMATICA = "Tematica";
public static final String TAG_SISTEMA = "Sistema";
//employee id to pass with intent
public static final String TBMESA_ID = "mesa_id";
}
&#13;
PHP
<?php
//Importing Database Script
require_once('dbConnect.php');
//Getting values
$IDMestre = $_GET['IDMestre'];
//Creating sql query
$sql = "SELECT * FROM tbmesa WHERE IDMestre = '$IDMestre'";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"IDMesa"=>$row['IDMesa'],
"Nome"=>$row['Nome'],
//"Tematica"=>$row['Tematica']
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
&#13;