繁体   English   中英

Android Google Place API java.lang.NullPointerException错误

[英]Android Google Place API java.lang.NullPointerException error

我试图通过自定义适配器将餐厅名称和类别添加到卡视图中。 但是无论何时我运行程序,都会不断收到Java空指针异常。 我对此有些惊讶,我一直在浏览网络,但没有发现运气。 提前致谢!

 //Main:

package com.example.rifatrashid.compass;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
 import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rifat Rashid on 2/23/2015.
*/
public class chooseactivity extends ActionBarActivity{
private ListView listView1;
ArrayList<Places> venuesList;
final String GOOGLE_KEY = "AIzaSyD72cNSZ6PoMFwvDe-ihUDNcTrAnuMynuE";
TextView t1;
final String latitude = "40.7463956";
final String longitude = "-73.9852992";
PlacesAdapter adapter1;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chooselocation);
    new googleplaces().execute();

    /*Places place_data[] = new Places[]{
      new Places("Lunch", "Mandarin Cuisine"),
      new Places("Brunch", "Fredmeyer"),
      new Places("Supplies", "Target")
    };
    */
    /*
   PlacesAdapter adapter = new PlacesAdapter(this, R.layout.listview_item_row, place_data);
   listView1 = (ListView) findViewById(R.id.listView);
    listView1.setAdapter(adapter);
    */
}
class googleplaces extends AsyncTask<View, Void, String> { //Line54
    String temp;

    @Override
    protected String doInBackground(View... urls) {
        temp = makeCall("https://maps.googleapis.com/maps/api/place/search/json?location=" + latitude + "," + longitude + "&radius=100&sensor=true&key=" + GOOGLE_KEY);
        return "";
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onPostExecute(String result) {
        if (temp == null) {
            //Error coce exception
        } else {
            venuesList = (ArrayList<Places>) parseGoogleParse(temp);
            List<String> listTitle = new ArrayList<>();
            //List<Places> gPlace = new ArrayList<>();
            Places[] place_data = new Places[100];
            for (int i = 0; i < venuesList.size(); i++) {
                //listTitle.add(i, venuesList.get(i).getName() + "\nOpen Now: " + venuesList.get(i).getOpenNow() + "\n(" + venuesList.get(i).getCategory() + ")");
                new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
                //gPlace.add(new Places(venuesList.get(i).getCategory(), "y"));
            }
             adapter1 = new PlacesAdapter(chooseactivity.this, R.layout.listview_item_row, place_data);
            listView1 = (ListView) findViewById(R.id.listView);
            listView1.setAdapter(adapter1);
        }
    }
}
public static String makeCall(String url) {

    // string buffers the url
    StringBuffer buffer_string = new StringBuffer(url);
    String replyString = "";

    // instanciate an HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    // instanciate an HttpGet
    HttpGet httpget = new HttpGet(buffer_string.toString());

    try {
        // get the responce of the httpclient execution of the url
        HttpResponse response = httpclient.execute(httpget);
        InputStream is = response.getEntity().getContent();

        // buffer input stream the result
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        // the result as a string is ready for parsing
        replyString = new String(baf.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(replyString);

    // trim the whitespaces
    return replyString.trim();
}

private static ArrayList<Places> parseGoogleParse(final String response) {
    ArrayList<Places> temp = new ArrayList<>();
    try {
        JSONObject jsonObject = new JSONObject(response);
        if (jsonObject.has("results")) {
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            for (int i = 0; i < jsonArray.length(); i++) {
                Places poi = new Places();
                if (jsonArray.getJSONObject(i).has("name")) {
                    poi.setName(jsonArray.getJSONObject(i).optString("name"));
                    poi.setRating(jsonArray.getJSONObject(i).optString("rating", " "));

                    if (jsonArray.getJSONObject(i).has("opening_hours")) {
                        if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").has("open_now")) {
                            if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").getString("open_now").equals("true")) {
                                poi.setOpenNow("YES");
                            } else {
                                poi.setOpenNow("NO");
                            }
                        }
                    } else {
                        poi.setOpenNow("Not Known");
                    }
                    if (jsonArray.getJSONObject(i).has("types")) {
                        JSONArray typesArray = jsonArray.getJSONObject(i).getJSONArray("types");

                        for (int j = 0; j < typesArray.length(); j++) {
                            poi.setCategory(typesArray.getString(j) + ", " + poi.getCategory());
                        }
                    }
                }
                temp.add(poi);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return new ArrayList<Places>();
    }
    return temp;

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}
}

这是我的地方课程:

package com.example.rifatrashid.compass;

/**
 * Created by Rifat Rashid on 2/23/2015.
 */
public class Places {
public String category;
public String name;
public String rating;
public String open;
public Places(){
    super();
}

public Places(String category, String name){
    super();
    this.category = "";
    this.name = "";
    this.rating = "";
    this.open = "";

}
public String getCategory(){
    return  category;
}
public String getOpen(){
    return open;
}
public String getName(){
    return name;
}

public void setName(String name) {
    this.name = name;
}

public void setRating(String rating) {
    this.rating = rating;
}

public void setOpenNow(String openNow) {
    this.open = openNow;
}

public void setCategory(String s) {
}

public String getOpenNow() {
    return open;
}
}

我的自定义适配器类:

package com.example.rifatrashid.compass;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places> {
Context context;
int layoutResourceId;
Places[] data;
//List<Places> data;


public PlacesAdapter(Context context, int layoutResourceId, Places[] data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}




public View getView(int position, View convertView, ViewGroup parent){
    View row = convertView;
    PlacesHolder holder = null;

    if(row == null){
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);

        holder = new PlacesHolder();

        holder.titleTxt = (TextView) row.findViewById(R.id.placeTitle);
        holder.sub = (TextView) row.findViewById(R.id.placeCategory);


        row.setTag(holder);

    }else{
        holder = (PlacesHolder) row.getTag();
    }
    Places place = data[position];
    holder.titleTxt.setText(place.getName());
    holder.sub.setText(place.getCategory());
    return row;
}

static class PlacesHolder{
    TextView titleTxt, sub;
}
}

错误:

02-26 17:05:30.530    9757-9757/com.example.rifatrashid.compass E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rifatrashid.compass, PID: 9757
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
        at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:77)
        at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:54)
        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:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        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:898)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

如错误日志所述,您在chooseactivity活动的googleplaces类中的onPostExecute方法中的一行存在问题。 (第77行)

具体来说,您要调用toString()的元素之一为null。

new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77

要修复错误(但不一定要修复您的过程),请将其包装在if语句中,该语句检查元素是否为null。 像这样:

if (venuesList.get(i) != null && venuesList.get(i).getCategory() != null && venuesList.get(i).getName() != null) {
    new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
}

现在,这实际上不会修复您的代码,只是防止发生此错误。 您真正应该做的是在Android Studio中,在第77行上放置一个断点,以便在调试时可以确切地看到哪个元素为null并追溯为什么可能是这种情况以及将来如何拦截它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM