php - 解析单个值到android

时间:2014-09-04 11:06:08

标签: java php android mysql json

我尝试编写一个简单的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());


        }

    }

这很有效,这是String" 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

2 个答案:

答案 0 :(得分:1)

我不确定你是如何实现它的,但是我假设你用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控制台中显示消息。

答案 1 :(得分:0)

我几个月前遇到过这个问题:

问题是,String str不仅包含单词“yes”。它还包含不同的字母/符号,这些字母/符号不会显示在Android / Eclipse中。所以你必须通过简单地调用substring(int start,int end)

来手动删除这些字母

试试这个:

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);