我从MongoDB发出http请求,并成功显示了我从请求中获得的列表。现在,当我点击ListView项目时,我获得用户全名,但我无法获得用户ID(Mongo ID)。我怎么能这样做?
用户类:
public class User implements Serializable {
private String user_id;
private String name;
private String username;
private String password;
public User( String user_id, String name, String username, String password) {
this.nom_prenom = nom_prenom;
this.username = username;
this.password = password;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
在我的活动中,我说:
for (int i = 0; i < data.length(); i++) {
try {
JSONObject userJson = data.getJSONObject(i);
if (userJson.has("_id") && userJson.has("name") && userJson.has("password")
&& userJson.has("username")) {
JSONObject idJson = userJson.getJSONObject("_id");
String user_id = idJson.getString("$oid");
String name = userJson.getString("name");
String username = userJson.getString("username");
String password = userJson.getString("password");
rentalProperties.add(new user(user_id, name, username, password));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//...
FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();
UsersFragment usersFrag = UsersFragment.newInstance(rentalProperties);
fragTrans.replace(R.id.fragment_view, usersFrag, "MY_FRAGMENT");
fragTrans.commit();
mfragment_view.setVisibility(View.VISIBLE);
我还有基于&#34; rentalProperties&#34;的适配器。我得到用户的名字:
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User obj = adapter.getItem(position);
String user_id = (String) obj.getUser_id();
String name = (String) obj.getName();
Log.e("User", user_id);
Intent intent = new Intent(getContext(), MainDisponibilitesActivity.class);
intent.putExtra(UserChoosedId, user_id);
intent.putExtra(UserChoosedName, name);
startActivity(intent);
}
我希望这可以解释我的情况。我的文件太多了。 感谢
答案 0 :(得分:0)
如果要从列表视图项(而不是列表位置)获取Id,则需要在从MongoDB检索数据时将该Id添加到列表视图项的模型中。如果您没有从数据库中向列表视图项模型添加任何ID,则单击列表视图项时您没有任何ID。