我尝试从 JSON 文件中获取单个字符串。
此文件使用存储在 MySql 数据库中的数据。
以下 logcat 显示了问题:
09-03 20:05:04.825: E/pass 1(27476): connection success
09-03 20:05:04.825: E/pass 2(27476): connection success
09-03 20:05:04.830: E/Fail 3(27476): org.json.JSONException: Value 29 of type
java.lang.String cannot be converted to JSONObject
我知道这个错误在 Stackoverflow 上的许多问题中都得到了解决,并且我尝试了所有解决方案:
- 在每个文档中使用 UTF-8
- 对每个字符串进行 substring()
- ...
同时我认为这是一个“代码”问题,肯定有什么问题。
所有代码部分均来自本教程:
请看一下:
Android Activity :
> try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myserver/msqlup.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
String name=(json_data.getString("$new"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
msqlup.php
<?php
$host='localhost';
$uname='myname';
$pwd='mypw';
$db="mydb";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$r=mysql_query("SELECT Coins from table WHERE new= 1234567");
$abfrage = "
SELECT
Coins
FROM
lunation";
$ergebnis = mysql_query($abfrage) OR die(mysql_error());
while($zeile = mysql_fetch_assoc($ergebnis)){
$new=$zeile["Coins"];
}
print(json_encode($new));
?>
这就是我想做的: 1.从数据库“表”中获取“硬币”的值 2.使用字符串将其保存在Android Activity中
我很感激任何建议(:
最佳答案
您的 result
变量似乎不是有效的 JSONObject
,因为它只包含 String
“29”。
在 PHP json_encode
中,仅适用于对象和数组,因此我会将您的 $new
变量添加到对象或数组,然后在 Android 客户端上创建new JSONObject(result)
或 new JSONArray(result)
,具体取决于您选择 json_encode
关于php - 从 JSON 获取数据会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25650991/