使用ion-koush库时JsonArray.toString()空对象引用问题求助
解决你的Ion库JSON为空与TableView插入问题
让我们一步步排查并解决你的问题,从后端PHP到Android前端逐一梳理:
1. 先修复PHP端的数据丢失bug
你的encodequery函数里有个致命问题:你先用mysqli_fetch_array($result)做判断,这会直接消耗掉结果集的第一行数据!如果数据库里只有一条数据,这个判断会把唯一的行读走,后面的while循环根本不会执行,最终返回的posts数组就是空的,这也是你前端拿到空JSON的核心原因之一。
修改后的PHP代码:
function encodequery($query) { $dbhost = "localhost"; $dbuser = "id1341573_267admin"; $db = "id1341573_rotc"; $dbpass = "iloveyou267"; $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s ". $conn -> error); $result = mysqli_query($conn, $query) or die(mysqli_error($conn)); $posts = array(); // 直接循环读取所有结果,不需要多余的判断 while($post = mysqli_fetch_assoc($result)) { $posts[] = array('post'=> $post); } encodearray($posts); }
2. 修正Android端Ion请求的类型不匹配
你用.asJsonArray()来请求接口,但你的PHP返回的是一个包裹着数组的JSONObject(结构是{"posts": [...]}),不是纯JSONArray。这会导致Ion解析失败,最终result为空。
修改后的Android请求代码:
Ion.with(this) .load("http://267.site11.com/doubletime-app/sql.php") // 改成请求JsonObject,匹配后端返回格式 .asJsonObject() .setCallback(new FutureCallback<JsonObject>() { @Override public void onCompleted(Exception e, JsonObject result) { // 先处理请求异常 if (e != null) { e.printStackTrace(); return; } // 打印返回的JSON,方便调试 System.out.println("后端返回的JSON: " + result.toString()); try { // 从JsonObject中取出posts数组 JSONArray arr = new JSONArray(result.get("posts").toString()); for (int i = 0; i < arr.length(); i++) { JSONObject postWrapper = arr.getJSONObject(i); JSONObject post = postWrapper.getJSONObject("post"); // 取出字段值 String id = post.getString("id"); String userid = post.getString("userid"); String password = post.getString("password"); String role = post.getString("role"); // 添加到表格 buildtable(id, userid, password, role); } } catch (JSONException E) { E.printStackTrace(); } } });
3. 补充:确保buildtable方法正确实现
你没贴出buildtable的代码,这里给你一个标准实现,确保能正确往TableLayout里添加数据行:
private void buildtable(String id, String userid, String password, String role) { // 加载行布局(和你的表头布局testlol一致即可) View tableRow = LayoutInflater.from(this).inflate(R.layout.testlol, null, false); TextView idTv = tableRow.findViewById(R.id.idtest); TextView userIdTv = tableRow.findViewById(R.id.useridtest); TextView passwordTv = tableRow.findViewById(R.id.passwordtest); TextView roleTv = tableRow.findViewById(R.id.roletest); // 设置文本内容 idTv.setText(id); userIdTv.setText(userid); passwordTv.setText(password); roleTv.setText(role); // 添加到表格 usertabletest.addView(tableRow); }
4. 最后检查:网络权限
别忘了在你的AndroidManifest.xml里添加网络权限,否则请求会失败:
<uses-permission android:name="android.permission.INTERNET" />
按照上面的步骤修改后,应该就能正常获取JSON数据并插入到TableView里了。调试时可以多打印日志,看看每一步的结果是否符合预期~
内容的提问来源于stack exchange,提问作者Raymond Manauis
相关产品推荐
相关产品推荐

