我尝试编写一个简单的php文件,检查mysql值是否存在。
为此,我需要解析从json到android的一个简单字符串。
当值存在时,字符串是"yes“,当它不存在时,字符串是"no”。
同时,我尝试了很多“解决方案”,但都没有效果。
为了做到这一点,我通常使用以下方法:
$abfrage = "
SELECT
Something
FROM
somewhere
WHERE
This=$that"
;
$link = mysql_query($abfrage) OR die("Error:"+mysql_error());
while($line = mysql_fetch_assoc($link)){
$new=$line;
}
print(json_encode($new));在Android系统中:
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
{
System.out.println(result);
json_data = new JSONObject(result);
String name=(json_data.getString("something"));
Log.e("pass 3", "connection success ");
}
catch(Exception e)
{
Log.e("result:", result.toString());
}
}这很好,字符串"name“的值是”某事“的值。
,但现在我的问题是:
是否可以将字符串保存在PHP中并将其解析为android?
,这就是我得到的:
$abfrage = "SELECT Something FROM somewhere WHERE This = '$that' LIMIT 1";
// Proof whether the value exists or not
$read = mysql_db_query($db, $abfrage);
if (mysql_num_rows($read) == 0){
$value="no";
}
else{
$value="yes";
};
print json_encode($value);在JAVA中:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/test.php");
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
System.out.println(""+str); //prints: yes
if(str=="yes") System.out.println("ok"); //not called
if(str=="no") System.out.println("nope"); //not called发布于 2014-09-04 12:20:23
几个月前,我遇到了这个问题:
的问题是,字符串str不仅包含单词"yes“。它还包含不同的字母/符号,这些字母/符号在Android/Eclipse中没有显示。因此,您必须手动删除这些字母,只需调用子字符串( int,int)
试试这个:
String str = EntityUtils.toString(response.getEntity());
int number= str.length();
System.out.println("str-length"+number); //You will see not the length of 3 (for yes)
String s2= str.substring(0, 3); //short the string
System.out.println("String s2"+s2);
if(s2.equals("yes"))Log.d("Titles", str);发布于 2014-09-04 11:16:23
我不知道您是如何实现它的,但我假设您是从java代码中执行PHP脚本的,如下所示:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample/sample.php");
HttpResponse response = httpclient.execute(httppost);然后简单地使用:
String str = EntityUtils.toString(response.getEntity());使用
Log.d("Title", "Message");若要在Logcat控制台中显示消息,请执行以下操作。
https://stackoverflow.com/questions/25663888
复制相似问题