我有一个Android应用程序,并使用PHP脚本和JSON对象建立了与MySql数据库的连接。如何根据当前的“ Android客户端”用户名检查结果?如果该用户名位于列中(例如receiver
或sender
),我只想显示当前用户名的消息。
我该怎么解决?如何检查在某些列中是否存在进行连接的用户名(并使用JSON对象获取结果)?
有人有主意吗?
在php脚本中查询。我认为无法将当前用户名发送到php脚本以查看某列中是否存在
$sql = "SELECT users.username, `message` FROM users, messages
WHERE msg_fk_user_id = users.id";
机器人活动-下载php脚本并使用JSON对象对结果进行编码。
public class ViewDbMessages extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_db_messages);
listView = (ListView) findViewById(R.id.listView);
downloadJSON("http://192.168.00.00/socketIO/examples/chat/public/android_db_connection.php");
}
private void downloadJSON(final String urlWebService) {
class DownloadJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] stocks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
stocks[i] = obj.getString("username") + ": " + obj.getString("message");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stocks);
listView.setAdapter(arrayAdapter);
}
}