iservice list方法_尝试调用接口方法'int java.util.List.size()

FATAL EXCEPTION: main

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

I try to find nearby place .... this kind of error I get.... help me

What kind of changes i apply plz guide me

public class MapsActivity extends FragmentActivity implements LocationListener{

GoogleMap mGoogleMap;

Spinner mSprPlaceType;

String[] mPlaceType=null;

String[] mPlaceTypeName=null;

double mLatitude=0;

double mLongitude=0;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);

// Array of place types

mPlaceType = getResources().getStringArray(R.array.place_type);

// Array of place type names

mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

// Creating an array adapter with an array of Place types

// to populate the spinner

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

// Getting reference to the Spinner

mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

// Setting adapter on Spinner to set place types

mSprPlaceType.setAdapter(adapter);

Button btnFind;

// Getting reference to Find Button

btnFind = ( Button ) findViewById(R.id.btn_find);

// Getting Google Play availability status

int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

int requestCode = 10;

Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);

dialog.show();

}

else

{ // Google Play Services are available

// Getting reference to the SupportMapFragment

SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting Google Map

mGoogleMap = fragment.getMap();

// Enabling MyLocation in Google Map

mGoogleMap.setMyLocationEnabled(true);

// Getting LocationManager object from System Service LOCATION_SERVICE

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider

Criteria criteria = new Criteria();

// Getting the name of the best provider

String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location From GPS

Location location = locationManager.getLastKnownLocation(provider);

if(location!=null){

onLocationChanged(location);

}

locationManager.requestLocationUpdates(provider, 20000, 0, this);

// Setting click event lister for the find button

btnFind.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

int selectedPosition = mSprPlaceType.getSelectedItemPosition();

String place = mPlaceTypeName[selectedPosition];

Toast.makeText(getApplicationContext(),"working",Toast.LENGTH_LONG).show();

StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");

sb.append("types=place");

sb.append("&location="+mLatitude+", "+mLongitude);

sb.append("&radius=10000");

sb.append("&sensor=true");

sb.append("&key=[My API Key]");

// Creating a new non-ui thread task to download json data

PlacesTask placesTask = new PlacesTask();

// Invokes the "doInBackground()" method of the class PlaceTask

placesTask.execute(sb.toString());

Toast.makeText(getApplicationContext(),"working",Toast.LENGTH_LONG).show();

}

});

}

}

/** A method to download json data from url */

private String downloadUrl(String strUrl) throws IOException{

String data = "";

InputStream iStream = null;

HttpURLConnection urlConnection = null;

try{

URL url = new URL(strUrl);

// Creating an http connection to communicate with url

urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url

urlConnection.connect();

// Reading data from url

iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";

while( ( line = br.readLine()) != null){

sb.append(line);

}

data = sb.toString();

br.close();

}catch(Exception e){

Log.d("Exception while downloading url", e.toString());

}finally{

iStream.close();

urlConnection.disconnect();

}

return data;

}

/** A class, to download Google Places */

private class PlacesTask extends AsyncTask{

String data = null;

// Invoked by execute() method of this object

@Override

protected String doInBackground(String... url) {

try{

data = downloadUrl(url[0]);

}catch(Exception e){

Log.d("Background Task",e.toString());

}

return data;

}

// Executed after the complete execution of doInBackground() method

@Override

protected void onPostExecute(String result){

ParserTask parserTask = new ParserTask();

// Start parsing the Google places in JSON format

// Invokes the "doInBackground()" method of the class ParseTask

parserTask.execute(result);

}

}

/** A class to parse the Google Places in JSON format */

private class ParserTask extends AsyncTask>>{

JSONObject jObject;

// Invoked by execute() method of this object

@Override

protected List> doInBackground(String... jsonData) {

List> places = null;

PlaceJSONParser placeJsonParser = new PlaceJSONParser();

try{

jObject = new JSONObject(jsonData[0]);

/** Getting the parsed data as a List construct */

places = placeJsonParser.parse(jObject);

}catch(Exception e){

Log.d("Exception",e.toString());

}

return places;

}

// Executed after the complete execution of doInBackground() method

@Override

protected void onPostExecute(List> list){

// Clears all the existing markers

mGoogleMap.clear();

for(int i=0;i

// Creating a marker

MarkerOptions markerOptions = new MarkerOptions();

// Getting a place from the places list

HashMap hmPlace = list.get(i);

// Getting latitude of the place

double lat = Double.parseDouble(hmPlace.get("lat"));

// Getting longitude of the place

double lng = Double.parseDouble(hmPlace.get("lng"));

// Getting name

String name = hmPlace.get("place_name");

// Getting vicinity

String vicinity = hmPlace.get("vicinity");

LatLng latLng = new LatLng(lat, lng);

// Setting the position for the marker

markerOptions.position(latLng);

// Setting the title for the marker.

//This will be displayed on taping the marker

markerOptions.title(name + " : " + vicinity);

// Placing a marker on the touched position

mGoogleMap.addMarker(markerOptions);

}

}

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

}

@Override

public void onLocationChanged(Location location) {

mLatitude = location.getLatitude();

mLongitude = location.getLongitude();

LatLng latLng = new LatLng(mLatitude, mLongitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}

@Override

public void onProviderDisabled(String provider) {

// TODO Auto-generated method stub

}

@Override

public void onProviderEnabled(String provider) {

// TODO Auto-generated method stub

}

@Override

public void onStatusChanged(String provider, int status, Bundle extras) {

// TODO Auto-generated method stub

}

}

Log:

08-19 14:52:02.145 22460-22460/com.example.admin.newmapplace E/AndroidRuntime﹕ FATAL EXCEPTION: main

Process: com.example.admin.newmapplace, PID: 22460

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

at com.example.admin.newmapplace.MapsActivity$ParserTask.onPostExecute(MapsActivity.java:245)

at com.example.admin.newmapplace.MapsActivity$ParserTask.onPostExecute(MapsActivity.java:215)

at android.os.AsyncTask.finish(AsyncTask.java:636)

at android.os.AsyncTask.access$500(AsyncTask.java:177)

at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)

at android.os.Handler.dispatchMessage(Handler.java:102)

at android.os.Looper.loop(Looper.java:135)

at android.app.ActivityThread.main(ActivityThread.java:5254)

at java.lang.reflect.Method.invoke(Native Method)

at java.lang.reflect.Method.invoke(Method.java:372)

at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

解决方案

The error is quite explanatory:

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

at com.example.admin.newmapplace.MapsActivity$ParserTask.onPostExecute(MapsActivity.java:245)

at com.example.admin.newmapplace.MapsActivity$ParserTask.onPostExecute(MapsActivity.java:215)

If you check in the ParserTask onPostExecute, that line (215 or 245) should be:

for(int i=0;i

And the issue is that, that method receives a null "list" item, which is taken from the method parameter:

protected void onPostExecute(List> list){

It is null because your "doInBackground" method returns a null object, looking at your code:

@Override

protected List> doInBackground(String... jsonData) {

List> places = null;

PlaceJSONParser placeJsonParser = new PlaceJSONParser();

try{

jObject = new JSONObject(jsonData[0]);

/** Getting the parsed data as a List construct */

places = placeJsonParser.parse(jObject);

}catch(Exception e){

Log.d("Exception",e.toString());

}

return places;

}

It seems that an exception is raised and then "places" is not set, leading to a null object returned. If you check the log (you set Debug, it's better to do Log.e in this cases), you should se a line with "Exception" and the text of the exception.

An alternative for logging exception:

Log.e(TAGOFMESSAGE,"Raised an exception during doInBackground Method",e);

This will log an error and will put the stack trace of the exception in the log, helping you understanding what raised the exception.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值