当jsonResponse从mySQL-DB获取空数据时,没有任何反应

时间:2017-09-06 07:12:10

标签: java php android mysql json

我刚接触java / android编程。

我正在编写一个应用程序,用户可以在其中注册并登录。数据保存在在线mysql-db中。注册和登录工作正常。用户使用会话保持loggig。

即使从mysql-db中获取数据也可以,但是当一些数据库字段响应时会出现一个问题" null"。

这是使用

的代码
    public class UserProfileSettingsFragment extends PreferenceFragment
{

    SessionManager session;

    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        SharedPreferences prefs = this.getActivity().getSharedPreferences("JampSharedPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.usersettings);

        session = new SessionManager(this.getActivity().getApplicationContext());



        HashMap<String,String> user = session.getUserDetails();
        final String sessionUsername = user.get(SessionManager.KEY_USERNAME);

        // ResponseListener um Request Nutzerdaten auszulesen.
        Response.Listener<String> UserDataResponseListener = new Response.Listener<String>(){
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");

                    // Wenn Datenabfrage erfolgreich, JSONResponse auswerten.
                    if (success) {
                        String responseRealName   = jsonResponse.getString("realname");
                        String responseStreetName = jsonResponse.getString("streetname");
                        int    responsePostcode   = jsonResponse.getInt   ("postcode");
                        String responseCity       = jsonResponse.getString("city");
                        String responseState      = jsonResponse.getString("state");
                        int    responseAge        = jsonResponse.getInt   ("age");
                        int    responseIsPremium  = jsonResponse.getInt   ("isPremium"); // BOOLEAN

                        Preference prefUserData = (Preference) findPreference("preferencescreen_userdata");
                        prefUserData.setTitle(sessionUsername);
                        //prefUserData.setSummary(responseRealName+"\n"+responseStreetName+"\n"+responsePostcode + " " + responseCity);

                        Preference prefUsername = (Preference) findPreference("settings_username");
                        prefUsername.setTitle(sessionUsername);

                        Toast.makeText(getActivity(),sessionUsername, Toast.LENGTH_LONG);

                        if (responseIsPremium==1){
                            //ivPremiumIcon.setVisibility(View.VISIBLE);
                        }


                    }else{
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
                                .setNegativeButton("Nochmal",null)
                                .create()
                                .show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }


        };

        // Request an userdatarequest.php senden
        UserDataRequest userDataRequest = new UserDataRequest(sessionUsername, UserDataResponseListener);
        RequestQueue queue = Volley.newRequestQueue(this.getActivity());
        queue.add(userDataRequest);


    }
}

PHP-代码:         

$con = mysqli_connect("localhost","web506","lalala","usr_web506_1");

$username = $_POST["username"];

$statement = mysqli_prepare($con,"SELECT * FROM user WHERE username = ?");

mysqli_stmt_bind_param($statement,"s",$username);
mysqli_stmt_execute($statement);

mysqli_stmt_store_result($statement);


mysqli_stmt_bind_result($statement, 
                        $userID, 
                        $username, 
                        $password, 
                        $email, 
                        $age, 
                        $realname, 
                        $streetname, 
                        $postcode, 
                        $city,
                        $state, 
                        $isPremium, 
                        $isLoggedIn);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;        
    $response["username"] = $username;
    $response["password"] = $password;
    $response["email"] = $email;
    $response["age"] = $age;
    $response["realname"] = $realname;
    $response["streetname"] = $streetname;
    $response["postcode"] = $postcode;
    $response["city"] = $city;
    $response["state"] = $state;
    $response["isPremium"] = $isPremium;
    $response["isLoggedIn"] = $isLoggedIn;

}

echo json_encode($response);

?>

因此,当我获取用户数据时,我可以使用Toast显示它们,更改preference.summaries或任何其他内容。但是如果某些mysql条目为空/ null则没有任何反应。该应用程序并没有崩溃,但它似乎没有得到成功&#34;来自php文件的布尔值。什么线索?

提前谢谢。 的Eirik

我应该删除$response["success"] = false;吗? 通常我得到一个警报消息,如果应用程序无法连接到数据库并且虚假布尔到达我的应用程序,所以我认为它就在那里。

当我在我的变量后面添加空白时,我知道他们的DB-cell是空的,那么jsonresponse会传递一个&#34; 0&#34;值为字符串结果如下:

      $response["realname"] = $realname+" ";
      $response["streetname"] = $streetname+" ";
      $response["postcode"] = $postcode+" ";
      $response["city"] = $city+" ";
      $response["state"] = $state+ " ";

我是一个文本视图,它们逐行显示为&#34; 0&#34;。

我是否必须在我的应用程序中解决这个问题,或者有一种简单的方法来以某种方式过滤空单元格并跳到下一个单元格?

2 个答案:

答案 0 :(得分:1)

    $response["success"] = true;
$record_size = 0;

while(mysqli_stmt_fetch($statement)){
    $response["success"] = true;        
    $response["username"] = $username;
    $response["password"] = $password;
    $response["email"] = $email;
    $response["age"] = $age;
    $response["realname"] = $realname;
    $response["streetname"] = $streetname;
    $response["postcode"] = $postcode;
    $response["city"] = $city;
    $response["state"] = $state;
    $response["isPremium"] = $isPremium;
    $response["isLoggedIn"] = $isLoggedIn;
    $record_size++;
}

$response["record_size"]  = $record_size;

echo json_encode($response);

对于我使用$ record_size变量的记录数,以便您可以了解记录。因为$ response [“success”] = true;意味着你成功地获得了数据库和记录,你可以使用$ response [“record_size”] ..我希望它能帮助你..

答案 1 :(得分:0)

我的解决方法现在看起来像这样: 如果我得到0值,我用xml recource中的“missing [...]”替换它们。

还有另一个不匹配...似乎我总是把我的jsonresponse作为一个字符串,但我想把我的第一个代码中的邮政编码作为整数,这也没有用。所以当我需要这种方式时,我将不得不将其解析为一个int。

String responseRealName   = jsonResponse.getString("realname");     if (responseRealName.equals("0"))   {responseRealName = getResources().getString(R.string.MissingRealName);}
                        String responseStreetName = jsonResponse.getString("streetname");   if (responseStreetName.equals("0")) {responseStreetName = getResources().getString(R.string.MissingStreetName);}
                        String responsePostcode   = jsonResponse.getString("postcode");     if (responsePostcode.equals("0"))   {responsePostcode = getResources().getString(R.string.MissingPostcode);}
                        String responseCity       = jsonResponse.getString("city");         if (responseCity.equals("0"))       {responseCity = getResources().getString(R.string.MissingCity);}
                        String responseState      = jsonResponse.getString("state");        if (responseState.equals("0"))      {responseState = getResources().getString(R.string.MissingState);}

我认为我的问题得到了足够的回答。