-4

I am getting Null pointer exception when I am accessing variable set by other method called earlier.

import android.util.Log;
public class StartActivity extends AppCompatActivity {

String lat, longi;
String soil_depth_db,soil_type_db,lulc_type_db,district_db;
String slope_db;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    lat = getIntent().getExtras().get("Latitude").toString();
    longi = getIntent().getExtras().get("Longitude").toString();

    getData(lat, longi);

    setData();
  }

private void setData(){
    Log.d("index",slope_db);
}


private void  getData(String lat, String longi){
    String URL = "http://10.129.133.157/test.php?x="+longi+"&y="+lat;
    Log.d("URL",URL);
    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, URL,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        Log.d("JSON",response);
                        JSONObject jsonObj = new JSONObject(response);
                        if(jsonObj.get("slope").equals(null))
                            slope_db = "1.0" ;
                        else
                            slope_db = (String) jsonObj.get("slope");
                        Log.d("slope",slope_db);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            },
            new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("TAG error","error occured"+error.toString());
                }
            }
    );
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);



}

When I comment line Log.d("index",slope_db); in setData() then it works fine otherwise it give NullPointer error. So value set in gatData which takes data from server is not being accessed by SetData() function.

sudhanshud
  • 101
  • 1

2 Answers2

0

Volley is executing asynchronously. slope_db is not getting set before the first completion of String request. getData() completes before slope_db is set and setData() is immediately executed on completion of getData(). Don't rely on async calls to initialize data that you'll need on the main thread, there's never a guarantee that the data will be initialized before you need it.

Either initialize the slope_db field (eg. String slope_db = "";), or don't use slope_db until after you're sure that it has been initialized by the asynchronous call.

Dan 0
  • 914
  • 7
  • 15
0

The string is an object in Java, so If you try to print "not initialised string", the program will occur NullPointerException.

When onCreate() event is occurred, slope_db is null.

Here is the example

String test;
System.out.println(test); //Complie error because not initialized

test = "";
System.out.println(test); //Ok
Pradeep
  • 9,667
  • 13
  • 27
  • 34
Pemassi
  • 612
  • 1
  • 7
  • 20