我需要将jsonArray的值发送到我的android代码才能填充listView。
这是我的rankingsReader.php
文件:
<?php
$serverName = "serverName";
$dbUsername = "dbUsername";
$dbPassword = "dbPassword";
$dbName = "dbName";
$tableName = "tableName";
$conn = new mysqli($serverName, $dbUsername, $dbPassword, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
try{
$sqlTopMembers = "SELECT XP, username FROM $tableName ORDER BY XP DESC LIMIT 10";
if (!($result = $conn->query($sqlTopMembers)))
die($conn->error);
if ($result->num_rows) {
$rankings = [];
while ($row = $result->fetch_assoc()) {
$rankings[] = $row;
}
echo json_encode(array($tableName => $rankings));
}
}catch (Exception $e){
echo "Error ", $e->getMessage();
}
这是我的jsonArray格式:
{"androidlogin":[{"XP":"24","username":"amin39"},{"XP":"24","username":"amin21"},{"XP":"3","username":"amin222"},{"XP":"2","username":"mahdi"},{"XP":"0","username":"amin49"},{"XP":"0","username":"amin20"},{"XP":"0","username":"amin22"},{"XP":"0","username":"Leopard"},{"XP":"0","username":"kjjkjhh"},{"XP":"0","username":"dashagh"}]}
我想在android中填充我的listView(rankings_list
)。
这是我的RankingListActivity.java
课程:
public class RankingListActivity extends MainPage {
private static final String link = "http://myapp.webhost.com/rankingsReader.php";
Connection rankingConnect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_ranking_list, (FrameLayout) findViewById(R.id.flContent));
ListView rankingsList = (ListView) findViewById(R.id.rankings_list);
setRanking();
}
private void setRanking() {
rankingConnect = new Connection(){
@Override
protected ProgressDialog createNewDialog(ProgressDialog dialog) {
dialog = new ProgressDialog(RankingListActivity.this);
return dialog;
}
@Override
protected String setUrl() {
return link;
}
};
}}
我已经阅读了一些关于Uri.Builder
和json
的内容,但我不知道如何在我的Android代码中使用它。请帮我用jsonArray的值填充我的listView(rankings_list
)。
答案 0 :(得分:1)
创建模型
排名列表数组模型
public class RankingList {
ArrayList<RankingList> androidLogin;
public ArrayList<RankingList> getAndroidLogin() {
return androidLogin;
}
public void setAndroidLogin(ArrayList<RankingList> androidLogin) {
this.androidLogin = androidLogin;
}
}
排名列表模型
public class RankingList {
String XP;
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getXP() {
return XP;
}
public void setXP(String XP) {
this.XP = XP;
}
}
创建一个getter和setter,然后用它来填充Gson.toJson()的数据;
Gson.toJson(your_string, RankingListArray.class);
这将完成工作