我尝试从JSON文件中获取单个String。
此文件使用存储在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上的许多问题都解决了这个错误,我尝试了所有解决方案:
同时我认为这是一个“代码”问题,一定是错误的。
所有代码部分都来自本教程:
请看一下:
Android活动:
> 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中我很感激任何建议(:
答案 0 :(得分:1)
您的result
变量似乎不是有效JSONObject
,因为它只包含String
&#34; 29&#34;。
在PHP json_encode
中只能真正用于对象和数组,因此我会将您的$new
变量添加到对象或数组中,然后在Android客户端上创建new JSONObject(result)
或new JSONArray(result)
取决于您选择json_encode
答案 1 :(得分:0)
更改
$new=$zeile["Coins"];
到
$new = $zeile;
然后在你的java中读取这个你需要:
String name = json_data.getString("Coins");
另请确保收到的回复为"Coins" : "29"
而不是"Coins" : 29
。