gpt4 book ai didi

java - Android Google Place API java.lang.NullPointerException 错误

转载 作者:行者123 更新时间:2023-12-02 04:56:07 26 4
gpt4 key购买 nike

我尝试通过自定义适配器将餐厅名称和类别添加到卡片 View 中。然而,每当我运行该程序时,我总是收到 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)

最佳答案

正如您的错误日志所示,您的 choiceactivity Activity 的 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,并回溯为什么会出现这种情况以及将来如何拦截它。

关于java - Android Google Place API java.lang.NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28755872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com