Eirik Fesker
Eirik Fesker

Reputation: 336

Nothing happens when jsonResponse gets null data from mySQL-DB

im just new to java/android programming.

Im writing an app, where users can register themselves and login. data is saved in an online mysql-db. registering and login is working fine. The user stays loggig by using a session.

Even fetching the data from the mysql-db works but theres one issue when some db fields are responsing "null".

this is the code im working with

    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-Code:

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

?>

So, when i fetch user data i can display them with Toast, change preference.summaries or whatsoever. But if some of the mysql entries are empty/null then nothing happens. the application doesn't crash but it seems that it doesnt get the "success" boolean from the php-file. whats the clue?

thanks in advance. eirik


should i delete the $response["success"] = false;? usually i get an alertmessage if the app can't connect to the database and the false bool reaches my application, so i thought its right there.

When i add blanks behind my variables from which i know their DB-cells are empty then jsonresponse delivers a "0" value as string result like this:

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

i a textview are they displayed row by row as "0".

do i have to work around this inside my application or is there an easy way to filter empty cells somehow and skip to the next one?

Upvotes: 1

Views: 82

Answers (2)

Eirik Fesker
Eirik Fesker

Reputation: 336

My workaround looks now like this: if i get 0 values i replace them with a "missing [...]" from an xml recource.

There was another mismatch too.. it seems that i get my jsonresponse always as a string, but i wanted to get the postcode in my first code as an integer, this didnt work too. so i will have to parse it to an int when i need it this way.

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

i think my question has been answered enough.

Upvotes: 0

Khushvinder
Khushvinder

Reputation: 298

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

For number of records I am using $record_size variable so that you can get the idea about records. because $response["success"] = true; means you are successfully able to get the DB and for records you can use $response["record_size"].. I hope it will help you..

Upvotes: 1

Related Questions