需要不兼容的类型 java.lang.string 发现 java.lang.object
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35553958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incompatible types required java.lang.string found java.lang.object
提问by MzeeJ
I'm following thistutorial to be able to implement Google Places API on a search view. I'm getting the following error on this line:
我正在关注本教程,以便能够在搜索视图上实现 Google Places API。我在这一行收到以下错误:
Incompatible types required java.lang.string found java.lang.object
需要不兼容的类型 java.lang.string 发现 java.lang.object
@Override
public String getItem(int index) {
return resultList.get(index);
}
Code snippet:
代码片段:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
}
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList autocomplete(String input) {
ArrayList resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&components=country:gr");
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
System.out.println("============================================================");
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter implements Filterable {
private ArrayList resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public int getCount() {
return resultList.size();
}
@Override
public String getItem(int index) {
return resultList.get(index);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
Any ideas on how to rectify this?
关于如何纠正这个问题的任何想法?
回答by ewanc
The ArrayList resultList
does not have any type information assigned to it, so it is being treated as an Object. When you take something from this list in getItem()
you are expecting it to be a String, which is what is causing the error.
ArrayListresultList
没有分配任何类型信息,因此它被视为一个对象。当你从这个列表中取出一些东西时,getItem()
你期望它是一个字符串,这就是导致错误的原因。
You have two options to fix this. Either change the ArrayList to be ArrayList<String>
, or in getItem() cast the result to a String.
您有两个选择来解决这个问题。要么将 ArrayList 更改为ArrayList<String>
,要么在 getItem() 中将结果转换为 String。
回答by Kanchan Chowdhury
Change your getItem() method as following:
更改您的 getItem() 方法如下:
@Override
public String getItem(int index) {
return (String)resultList.get(index);
}
回答by Vikrant Kashyap
Kindly check Your StackTrace. You are able to resolve this error because only datatype
mismatch is being occured. Please embed your StackTraceto identify the line where this Exception
actually came.
请检查您的StackTrace。您能够解决此错误,因为仅datatype
发生不匹配。请嵌入您的StackTrace以识别Exception
实际出现的行。
Compile Time Error
编译时错误
requiredjava.lang.string
foundjava.lang.object
Read it carefully.
需要java.lang.string
找到java.lang.object
仔细阅读。
回答by f1sh
Change this line
改变这一行
private ArrayList resultList;
to this:
对此:
private ArrayList<String> resultList;