Android Volley - Throwing a Null Pointer Exception when calling .length() on a String, but I don't use .length() anywhere

时间:2016-07-11 23:15:20

标签: java php android mysql

So I am attempting to upload some data to a MySQL database. I'm pulling a variable from one class (LoginActivity) and putting it into another class (PartySetup) in order to pass this one variable along with some new ones into a MySQL database. Before attempting to pull this new variable, everything worked fine - the only changes I made were creating a public variable in LoginActivity, adding 'user' to the CreatePartyRequest, and fixing up my PHP.

Does anyone have any ideas why this is happening? I'm getting the error message Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference - I don't know what would be null here.

PartySetup.java:

public class PartySetup extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient mGoogleApiClient;
private Location location;
private TextView tempLatitude;
private TextView tempLongitude;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_party_setup);

    final EditText tempPartyName = (EditText) findViewById(R.id.party_name);
    final EditText tempHostName = (EditText) findViewById(R.id.host_name);
    final Button startParty = (Button) findViewById(R.id.create_party);
    final CheckBox locationButton = (CheckBox) findViewById(R.id.set_location);
    final String email = LoginActivity.publicEmail;
    tempLatitude = (TextView) findViewById(R.id.latitude_text);
    tempLongitude = (TextView) findViewById(R.id.longitude_text);

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mGoogleApiClient.connect();

        startParty.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if (locationButton.isChecked() && tempPartyName != null){
                    final String partyName = tempPartyName.getText().toString();
                    final String hostName;
                    if (tempHostName == null){
                        hostName = "";
                    }
                    else hostName = tempHostName.getText().toString();
                    final String latitude = tempLatitude.getText().toString();
                    final String longitude = tempLongitude.getText().toString();

                    Response.Listener<String> responseListener = new Response.Listener<String>(){
                        @Override
                        public void onResponse(String response){
                            try{
                                Log.i("TAG", response);
                                JSONObject jsonResponse = new JSONObject(response);
                                boolean success = jsonResponse.getBoolean("success");
                                if(success){
                                    Intent intent = new Intent(PartySetup.this, HomePage.class);
                                    startActivity(intent);
                                }
                                else{
                                    AlertDialog.Builder builder = new AlertDialog.Builder(PartySetup.this);
                                    builder.setMessage("Invalid Party Nickname")
                                            .setNegativeButton("Try Again", null)
                                            .create()
                                            .show();
                                }
                            } catch (JSONException e){
                                e.printStackTrace();
                            }
                        }
                    };

                    CreatePartyRequest createPartyRequest = new CreatePartyRequest(partyName, hostName, latitude, longitude, email, responseListener);
                    RequestQueue queue = Volley.newRequestQueue(PartySetup.this);
                    queue.add(createPartyRequest);
                }
                else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(PartySetup.this);
                    builder.setMessage("Please check the location box")
                            .setNegativeButton("Try Again", null)
                            .create()
                            .show();
                }
            }
        });
    }

protected void onStart() {
    mGoogleApiClient.connect();
    super.onStart();
}

protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    try{
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }
    catch (SecurityException e){
        e.printStackTrace();
    }
    if (location != null){
        tempLatitude.setText(String.valueOf(location.getLatitude()));
        tempLongitude.setText(String.valueOf(location.getLongitude()));
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

CreatePartyRequest.java:

public class CreatePartyRequest extends StringRequest {
private static final String CREATE_PARTY_REQUEST_URL = "http://10.0.2.2:8080/android_login_api/create_party_request.php";
private Map<String, String> params;

public CreatePartyRequest(String partyName, String hostName, String latitude, String longitude, String email, Response.Listener<String> listener){
    super(Method.POST, CREATE_PARTY_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("partyName", partyName);
    params.put("hostName", hostName);
    params.put("latitude", latitude);
    params.put("longitude", longitude);
    params.put("user", email);
}

@Override
public Map<String, String> getParams(){
    return params;
}
}

LoginActivity.java:

public class LoginActivity extends AppCompatActivity{

public static String publicEmail;

@Override
protected void onCreate(Bundle savedInstancedState){
    super.onCreate(savedInstancedState);
    setContentView(R.layout.activity_login);

    final EditText tempEmail = (EditText) findViewById(R.id.email);
    final EditText tempPassword = (EditText) findViewById(R.id.password);
    final Button loginButton = (Button) findViewById(R.id.btnLogin);
    final Button toRegisterScreen = (Button) findViewById(R.id.btnLinkToRegisterScreen);

    if (SaveSharedPreference.getUserName(LoginActivity.this).length() != 0){
        // If the user's already been logged in, skip the login screen
        Intent intent = new Intent(LoginActivity.this, OneTimeWelcome.class);
        startActivity(intent);
        finish();
    }

    toRegisterScreen.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
            LoginActivity.this.startActivity(registerIntent);
        }
    });

    loginButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            final String email = tempEmail.getText().toString();
            publicEmail = email;
            final String password = tempPassword.getText().toString();

            //Response received from the server
            Response.Listener<String> responseListener = new Response.Listener<String>(){
                @Override
                public void onResponse(String response){
                    try{
                        Log.i("TAG", response);
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");

                        if(success){
                            String name = jsonResponse.getString("name");

                            Intent intent = new Intent(LoginActivity.this, OneTimeWelcome.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            intent.putExtra("name", name);
                            intent.putExtra("email", email);
                            LoginActivity.this.startActivity(intent);
                            finish();
                        }
                        else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }
                    }
                    catch(JSONException e){
                        e.printStackTrace();
                    }
                    SaveSharedPreference.setUserName(LoginActivity.this, email);
                }
            };

            LoginRequest loginRequest = new LoginRequest(email, password, responseListener);
            RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
            queue.add(loginRequest);
        }
    });
}
}

create_party_request.php:

<?php

$con = mysqli_connect("127.0.0.1" , "[username]" , "[password]" , "android_api");

$partyName = $_POST["partyName"];
$hostName = $_POST["hostName"];
$latitude = $_POST["latitude"];
$longitude = $_POST["longitude"];
$email = $_POST["email"];

global $con, $partyName, $hostName, $latitude, $longitude;
$statement = mysqli_prepare($con, "INSERT INTO parties (party_name, host_name, latitude, longitude, email) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "sssss", $partyName, $hostName, $latitude, $longitude, $email);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);

$emailStatement = mysqli_prepare($con, "SELECT * FROM" )

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

echo json_encode($response); 
?>

Image of the error

1 个答案:

答案 0 :(得分:0)

该错误基本上表示&#39; SaveSharedPreference.getUserName(LoginActivity.this)&#39;一片空白。如果Prefs中的用户名中存储了某些内容,请先尝试检查。 如果我建议,请使用&#39; TextUtils.isEmpty(String)&#39;检查是否为空值或空值。