我正在尝试创建一个简单的函数,可以从邮政编码中找到信息。在下面提供的代码中,如果我输入有效的邮政编码,它将完全有效。但是当我输入错误的邮政编码时问题就开始了。我尝试使用语句try catch但不是显示错误完整的应用程序崩溃。我还想知道如何仅在英国限制搜索。通过邮政编码寻找地址是否有更好的选择,而不是使用getfromlocationName函数。
public void finder(String query){
Geocoder geocoder;
List<Address> addresses = new ArrayList<Address>();
geocoder = new Geocoder(this, Locale.getDefault());
try {
//addresses = geocoder.getFromLocation(51.283973, 1.064928, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
addresses = geocoder.getFromLocationName(query,1);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Fail " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
String street = addresses.get(0).getThoroughfare();
Log.i("I0",street);
String city = addresses.get(0).getLocality();
Log.i("I1",city);
String county = addresses.get(0).getSubAdminArea();
Log.i("I2",county);
String country = addresses.get(0).getCountryName();
Log.i("I3",country);
String postalCode = addresses.get(0).getPostalCode();
Log.i("I4",postalCode);
display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode ); }
错误是
07-13 21:15:26.717 10744-10744/com.example.mandeep.testing I/i1: ct3456
07-13 21:15:26.856 10744-10744/com.example.mandeep.testing D/AndroidRuntime: Shutting down VM
07-13 21:15:26.857 10744-10744/com.example.mandeep.testing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mandeep.testing, PID: 10744
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.mandeep.testing.MainActivity.finder(MainActivity.java:85)
at com.example.mandeep.testing.MainActivity$1.onQueryTextSubmit(MainActivity.java:47)
at android.widget.SearchView.onSubmitQuery(SearchView.java:1197)
at android.widget.SearchView.access$900(SearchView.java:92)
at android.widget.SearchView$8.onEditorAction(SearchView.java:1175)
at android.widget.TextView.onEditorAction(TextView.java:4473)
at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5219)
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)
07-13 21:15:26.878 10744-10744/? I/Process: Sending signal. PID: 10744 SIG: 9
我试过
if(addresses != null && addresses.size() > 0) {
String street = addresses.get(0).getThoroughfare();
Log.i("I0", street);
String city = addresses.get(0).getLocality();
Log.i("I1", city);
String county = addresses.get(0).getSubAdminArea();
Log.i("I2", county);
String country = addresses.get(0).getCountryName();
Log.i("I3", country);
String postalCode = addresses.get(0).getPostalCode();
Log.i("I4", postalCode);
display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode);
}
else{
Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
}
仍然是同样的问题。
我现在编辑了代码
public void finder(String query){
Geocoder geocoder;
List<Address> addresses = new ArrayList<Address>();
geocoder = new Geocoder(this, Locale.getDefault());
try {
//addresses = geocoder.getFromLocation(51.283973, 1.064928, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
addresses = geocoder.getFromLocationName(query,1);
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Fail " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
Log.i("yes",addresses.size() + "");
if(addresses != null && addresses.size() > 0) {
Log.i("yes","checked");
String street = addresses.get(0).getThoroughfare();
Log.i("I0", street);
String city = addresses.get(0).getLocality();
Log.i("I1", city);
String county = addresses.get(0).getSubAdminArea();
Log.i("I2", county);
String country = addresses.get(0).getCountryName();
Log.i("I3", country);
String postalCode = addresses.get(0).getPostalCode();
Log.i("I4", postalCode);
display.setText(street + "\n" + city + "\n" + country + "\n" + postalCode);
}
else{
Toast.makeText(MainActivity.this, "No Results Found", Toast.LENGTH_SHORT).show();
}
}
现在错误是
07-13 22:21:02.782 32088-32088/com.example.mandeep.testing I/i1: ct28dx
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing I/yes: 1
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing I/yes: checked
07-13 22:21:02.942 32088-32088/com.example.mandeep.testing D/AndroidRuntime: Shutting down VM
07-13 22:21:02.944 32088-32088/com.example.mandeep.testing E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mandeep.testing, PID: 32088
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.i(Log.java:160)
at com.example.mandeep.testing.MainActivity.finder(MainActivity.java:93)
at com.example.mandeep.testing.MainActivity$1.onQueryTextSubmit(MainActivity.java:52)
at android.widget.SearchView.onSubmitQuery(SearchView.java:1197)
at android.widget.SearchView.access$900(SearchView.java:92)
at android.widget.SearchView$8.onEditorAction(SearchView.java:1175)
at android.widget.TextView.onEditorAction(TextView.java:4473)
at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:139)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:304)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5219)
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)
07-13 22:21:02.973 32088-32088/com.example.mandeep.testing I/Process: Sending signal. PID: 32088 SIG: 9
答案 0 :(得分:2)
您应首先检查阵列的大小
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>THEMES</title>
<link rel="shortcut icon" href="https://assets.tumblr.com/images/default_avatar/sphere_closed_128.png">
<link rel="alternate" type="application/rss+xml" href="https://themesforyou.tumblr.com/rss">
<link href="https://fonts.googleapis.com/css?family=Unica+One" rel="stylesheet">
<script src="https://static.tumblr.com/iuw14ew/VSQma1786/jquery.style-my-tooltips.js"></script>
<div id="topbar">
<div id="title">Themes for you</div>
<div class="tabs">
<div class="titab home">Home</div>
<div class="titab contact">Contact</div>
<div class="titab submit">Submit</div>
<div class="titab links">Links</div>
</div>
</div>
<div class="tab home">
<div class="entries">
<div class="post">
<iframe width="500" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/LKn_3jOKCd8?feature=oembed&enablejsapi=1&origin=https://safe.txmblr.com&wmode=opaque" frameborder="0" allowfullscreen=""></iframe>
<p>Video example</p>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913245268/video-example">5:17 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/video-post">#video post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<iframe src="https://w.soundcloud.com/player/?url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F4595620&visual=true&liking=false&sharing=false&auto_play=false&show_comments=false&continuous_play=false&origin=tumblr" frameborder="0"
allowtransparency="true" class="soundcloud_audio_player" width="500" height="500"></iframe>
<p>Song example</p>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913201693/song-example">5:16 pm</a> <a href="http://soundcloud.com/rodrigovaz/johann-sebastian-bach-pachelbels-cannon-in-d-major">source</a></div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/song-post">#song post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<h1>Chat example</h1><b>Someone:</b> Hello!<br><b>Somebody:</b> How are you?<br><b>Someone:</b> Good. This is an example of a chat between two people<br>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913135663/chat-example">5:14 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/chat-post">#chat post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<h1><a href="http://t.umblr.com/redirect?z=http%3A%2F%2Ffr.lipsum.com%2F&t=NzM2ZDBmOWE1MjkxNjE3ZWE4MTVjZWY0YjhkMmYwYzA5MzFlMTcxOSxXMUV1V2RJNg%3D%3D&b=t%3Aug0c1iN6GrzkGIMg-nJ8Ww&p=https%3A%2F%2Fthemesforyou.tumblr.com%2Fpost%2F162913065653%2Florem-ipsum-all-the-facts-lipsum-generator&m=1">Lorem Ipsum - All the facts - Lipsum generator</a></h1>
<p>Link example</p>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913065653/lorem-ipsum-all-the-facts-lipsum-generator">5:12 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/link-post">#link post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<big><b>"This is what a quote looks like"</b></big>
<p></p>— Source
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913036513/this-is-what-a-quote-looks-like">5:11 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/quote-post">#quote post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<a href="https://themesforyou.tumblr.com/image/162913004603"><img src="https://68.media.tumblr.com/cf975a46b1a6b0183ea6e5017f56271c/tumblr_oszxhlV6bZ1wuevxyo1_500.png"></a>
<p>Photo example</p>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162913004603/photo-example">5:10 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/photo-post">#photo post</a> <a href="https://themesforyou.tumblr.com/tagged/post-example">#post example</a> </div>
<div class="postnote">
</div>
</div>
<div id="post">
<h1><big><big>Text example</big></big></h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras efficitur eget massa at mattis. Nulla ullamcorper massa ante, et bibendum sem ultricies et. In hac habitasse platea dictumst. Suspendisse tempus orci ex, fermentum accumsan velit pulvinar
a. Pellentesque vehicula, felis non fermentum suscipit, sem velit scelerisque urna, eu placerat velit lectus ut metus. Duis molestie scelerisque convallis. In ornare libero ipsum, eget rhoncus velit viverra a. Maecenas facilisis tellus metus,
ac consequat tellus tristique et. Aenean eu neque eu erat euismod euismod. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis in maximus ipsum.</p>
<p>Nullam ac dui et augue rhoncus condimentum facilisis in orci. Aenean sit amet metus magna. Mauris eu pellentesque velit. Nullam dui risus, varius nec sem pellentesque, suscipit consequat mauris. Vivamus volutpat, mi in molestie blandit, ligula
odio efficitur libero, ac porta leo tellus eu felis. Mauris auctor orci sagittis libero semper tristique. Praesent hendrerit purus ex, eget fermentum nulla maximus nec. Fusce nisi metus, scelerisque et mi vitae, posuere condimentum odio. Aenean
maximus erat non commodo aliquam. Aliquam ac tincidunt metus. Integer tincidunt id sapien lobortis imperdiet. Maecenas enim sem, vehicula sit amet feugiat sit amet, ornare vitae ex. Nam vulputate volutpat quam, a dapibus justo cursus vel. Donec
ac gravida nulla. In ultrices erat et dictum tristique.</p>
<div class="postinfo"> <a href="https://themesforyou.tumblr.com/post/162912904188/text-example">5:07 pm</a> </div>
<div class="tags">
<a href="https://themesforyou.tumblr.com/tagged/text-post">#text post</a> <a href="https://themesforyou.tumblr.com/tagged/example-post">#example post</a> </div>
<div class="postnote">
</div>
</div>
</div>
<!-- end entries-->
</div>
<!--end tab 1-->
<div class="tab contact">
<iframe class="inbox" frameborder="0" border="0" scrolling="no" width="350" height="260" allowtransparency="true" src="http://www.tumblr.com/ask_form/themesforyou.tumblr.com"></iframe>
</div>
<div class="tab submit">
<iframe class="inbox" frameborder="0" border="0" scrolling="no" width="350" height="260" allowtransparency="true" src="http://www.tumblr.com/submit_form/themesforyou.tumblr.com"></iframe>
</div>
<div class="tab links">
<div class="link">
<div class="tilink">Title</div>
<a href="/tagged/">Link 1</a>
<a href="/tagged/">Link 2</a>
<a href="/tagged/">Link 3</a>
<a href="/tagged/">Link 4</a>
</div>
<div class="link">
<div class="tilink">Title</div>
<a href="/tagged/">Link 1</a>
<a href="/tagged/">Link 2</a>
<a href="/tagged/">Link 3</a>
<a href="/tagged/">Link 4</a>
</div>
<div class="link">
<div class="tilink">Title</div>
<a href="/tagged/">Link 1</a>
<a href="/tagged/">Link 2</a>
<a href="/tagged/">Link 3</a>
<a href="/tagged/">Link 4</a>
</div>
</div>
</body>
</html>
你要从索引0获取数据,但你的列表是空的。
答案 1 :(得分:0)
此行geocoder.getFromLocationName(query,1);
返回一个空列表。可能是因为没有找到匹配项或者没有可用的后端服务(根据https://developer.android.com/reference/android/location/Geocoder.html)。在对列表执行操作之前,您应该检查addresses != null && addresses.size() > 0
是否为真。
答案 2 :(得分:0)
如前所述,不要假设Geocoder.getFromLocationName()
总是返回结果。它可以返回一个空数组。
此外:
Address.getLocality()
,Address.getAdminArea()
等可以返回null。你必须检查这个。Address.getAddressLine(int)
中的行数。使用Address.getMaxAddressLineIndex()
检查实际返回的行数。答案 3 :(得分:-1)
我遇到了同样的问题,然后我在开头声明了一个具有默认值的变量,因此,如果对请求有答复,则将覆盖该变量,否则将返回默认值。在这种情况下,您可以简单地写出“某些内容无法正常运行,请重试”或类似的内容。
fun getCountryCodeFromName(locationName: String = "California"): String {
var postalCode:String = "00000"
try {
if (find(locationName).size !=0)
countryCode = cityNameReq(locationName)[0].postalCode
} catch (e: Exception) {
resultMessage = Resources.getSystem().getString(R.string.catch_me)
Log.e(TAG, resultMessage, e)
}
return postalCode
}
基本上
`var postalCode:String = "00000"`
如果程序未转到try块并捕获异常,则会返回。
,如果请求成功,则postalCode将获得分配给它的新值,如您在此行中所见:
countryCode = cityNameReq(locationName)[0].postalCode
PS:我知道发问者已经很晚了,但是我将答案发送给仍然有此问题并正在寻找答案的人: