• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Status variable returns nullPointerException (Android)

How to solve status variable giving back null

  • Java,

    Votes: 0 0.0%
  • Android,

    Votes: 0 0.0%

  • Total voters
    0
I have been following a tutorial (http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/) in order to make a listview display nearest restaurant to your location in radius of 5km.

However i keep getting an error, in my Runnable it says that the status variable is null. I don't really understand why this error pops up. Can you guys give me a short explanation and help find a solution??


PlacesList.java
Java:
publicclassPlacesListimplementsSerializable{

publicString status;publicList<Place> results;

}

DisplayLocations.java
Java:
publicclassDisplayLocationsextendsActivity{

boolean isInternetPresent =false;

ConnectionDetector cd;GooglePlaces googlePlaces;PlacesList nearPlaces;GPSTracker gps;

Button shownOnMap;ProgressDialog pDialog;

ListView lv;

ArrayList<HashMap<String,String>> placesListItems =newArrayList<HashMap<String,String>>();

publicstaticString KEY_REFERENCE ="reference";publicstaticString KEY_NAME ="name";publicstaticString KEY_VICINITY ="vicinity";

@Overrideprotectedvoid onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_locations);

cd =newConnectionDetector(getApplicationContext());

isInternetPresent = cd.isConnectingToInternet();if(!isInternetPresent){Toast.makeText(getApplicationContext(),"Get a working connection",Toast.LENGTH_SHORT).show();return;}

gps =newGPSTracker(DisplayLocations.this);

if(gps.canGetLocation()){

}else{
gps.showSettingsAlert();}

lv =(ListView)findViewById(R.id.list);
shownOnMap =(Button)findViewById(R.id.btn_show_map);

newLoadPlaces().execute();

shownOnMap.setOnClickListener(newView.OnClickListener(){@Overridepublicvoid onClick(View v){/*
Intent i = new Intent(getApplicationContext(), PlacesMapActivity.class);
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
i.putExtra("near_places", nearPlaces);
startActivity(i);
*/}});

lv.setOnItemClickListener(newAdapterView.OnItemClickListener(){@Overridepublicvoid onItemClick(AdapterView<?> parent,View view,int position,long id){String reference =((TextView) findViewById(R.id.reference)).getText().toString();/*
Intent in = new Intent(getApplicationContext(), SingePlaceActivity.class);
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
*/}});}


classLoadPlacesextendsAsyncTask<String,String,String>{

@Overrideprotectedvoid onPreExecute(){super.onPreExecute();
pDialog =newProgressDialog(DisplayLocations.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();}

@OverrideprotectedString doInBackground(String... params){
googlePlaces =newGooglePlaces();

try{String types ="cafe|restaurant";double radius =5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);

}catch(Exception e){
e.printStackTrace();}returnnull;}

@Overrideprotectedvoid onPostExecute(String file_url){
pDialog.dismiss();

runOnUiThread(newRunnable(){@Overridepublicvoid run(){String status = nearPlaces.status;

if(status.equals("OK")){if(nearPlaces.results !=null){for(Place p : nearPlaces.results){HashMap<String,String> map =newHashMap<String,String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
placesListItems.add(map);}ListAdapter adapter =newSimpleAdapter(DisplayLocations.this, placesListItems, R.layout.location_listview_item,newString[]{KEY_REFERENCE, KEY_NAME},newint[]{R.id.reference, R.id.name});
lv.setAdapter(adapter);}}elseif(status.equals("ZERO_RESULTS")){// Zero results foundToast.makeText(getApplicationContext(),"No Results",Toast.LENGTH_SHORT);}elseif(status.equals("UNKNOWN_ERROR")){Toast.makeText(getApplicationContext(),"Unknown error",Toast.LENGTH_SHORT);}elseif(status.equals("OVER_QUERY_LIMIT")){Toast.makeText(getApplicationContext(),"Query limit reached !",Toast.LENGTH_SHORT);}elseif(status.equals("REQUEST_DENIED")){Toast.makeText(getApplicationContext(),"Request denied",Toast.LENGTH_SHORT);}elseif(status.equals("INVALID_REQUEST")){Toast.makeText(getApplicationContext(),"Invalid request",Toast.LENGTH_SHORT);}else{Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT);}}});}}

@Overridepublicboolean onCreateOptionsMenu(Menu menu){// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_display_locations, menu);returntrue;}

@Overridepublicboolean onOptionsItemSelected(MenuItem item){// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();

//noinspection SimplifiableIfStatementif(id == R.id.action_settings){returntrue;}

returnsuper.onOptionsItemSelected(item);}}

GooglePlaces.java

Java:
publicclassGooglePlaces{

privatestaticfinalHttpTransport HTTP_TRANSPORT =newNetHttpTransport();

privatefinalString API_KEY ="private but declared well in project";

//GooglePlaces search URLprivatestaticfinalString PLACES_SEARCH_URL ="https://maps.googleapis.com/maps/api/place/search/json?";privatestaticfinalString PLACES_TEXT_SEARCH_URL ="https://maps.googleapis.com/maps/api/place/search/json?";privatestaticfinalString PLACES_DETAILS_URL ="https://maps.googleapis.com/maps/api/place/details/json?";

privatedouble mLatitiude;privatedouble mLongitude;privatedouble mRadius;

publicPlacesList search(double latitude,double longitude,double radius,String types)throwsException{this.mLatitiude = latitude;this.mLongitude = longitude;this.mRadius = radius;

try{HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);HttpRequest request = httpRequestFactory.buildGetRequest(newGenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", mLatitiude +","+ mLongitude);
request.getUrl().put("radius", mRadius);// in meters
request.getUrl().put("sensor","false");if(types !=null)
request.getUrl().put("types", types);

PlacesList list = request.execute().parseAs(PlacesList.class);// Check log cat for places response statusLog.d("Places Status",""+ list.status);return list;

}catch(HttpResponseException e){Log.e("Error:", e.getMessage());returnnull;}

}

publicPlaceDetails getPlaceDetails(String reference)throwsException{try{HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);HttpRequest request = httpRequestFactory.buildGetRequest(newGenericUrl(PLACES_DETAILS_URL));
request.getUrl().put("reference", reference);
request.getUrl().put("key", API_KEY);
request.getUrl().put("sensor",false);

PlaceDetails place = request.execute().parseAs(PlaceDetails.class);return place;

}catch(HttpResponseException e){throw e;}}

publicstaticHttpRequestFactory createRequestFactory(finalHttpTransport transport){return transport.createRequestFactory(newHttpRequestInitializer(){@Overridepublicvoid initialize(HttpRequest request)throwsIOException{HttpHeaders httpHeaders =newHttpHeaders();
httpHeaders.setUserAgent("Application Test");
request.setHeaders(httpHeaders);JsonObjectParser parser =newJsonObjectParser(newJsonFactory(){@OverridepublicJsonParser createJsonParser(InputStream in)throwsIOException{returnnull;}

@OverridepublicJsonParser createJsonParser(InputStream in,Charset charset)throwsIOException{returnnull;}

@OverridepublicJsonParser createJsonParser(String value)throwsIOException{returnnull;}

@OverridepublicJsonParser createJsonParser(Reader reader)throwsIOException{returnnull;}

@OverridepublicJsonGenerator createJsonGenerator(OutputStream out,Charset enc)throwsIOException{returnnull;}

@OverridepublicJsonGenerator createJsonGenerator(Writer writer)throwsIOException{returnnull;}});
request.setParser(parser);}

});}}

This is the line that gives error

Java:
String status = nearPlaces.status;

Stacktrace
Java:
java.lang.NullPointerException:Attempt to read from field 'java.lang.String com.example.dell.exampleapplication.PlacesList.status' on a null object reference
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces$1.run(DisplayLocations.java:132)
at android.app.Activity.runOnUiThread(Activity.java:5517)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:129)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:98)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
at java.lang.reflect.Method.invoke(NativeMethod)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
I understand that the error is because status is giving null back, however i don't know how to resolve this. Any suggestions?
Thanks in advance,
 
First you need to know, what you get in this line, as String:
Code:
PlacesList list = request.execute().parseAs(PlacesList.class);
Maybe request.execute() not gives responce with status field
 
Back
Top Bottom