我尝试了一个用于解析JSONObjects的Volley教程,它工作得非常好,所以我想尝试在运行REST API的localhost上使用Volley JSONAarrayRequest。 My Ressource(url)返回一个具有以下结构的JSON数组:
[
{
"Latitude": 50.995739999999998,
"Stadt": "Köln",
"Beschreibung": "DRK",
"Longitude": 6.9249700000000001,
"Adresse": "Altonaer Str. 32",
"SRID": 4,
"Materialien Anzahl": 45,
"PLZ": "50737"
},
{
"Latitude": 50.997259999999997,
"Stadt": "Köln",
"Beschreibung": "Schreibwarenhandel Müller",
"Longitude": 6.9046219999999998,
"Adresse": "Grethenstraße 9",
"SRID": 3,
"Materialien Anzahl": 25,
"PLZ": "50739"
},
{
"Latitude": 50.998410999999997,
"Stadt": "Köln",
"Beschreibung": "Kath. Kirchen e.V",
"Longitude": 6.9066720000000004,
"Adresse": "Heimersdorfer Strasse 7",
"SRID": 1,
"Materialien Anzahl": 20,
"PLZ": "50739"
}
]
请求的My Java代码如下所示:
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest localJReq = new JsonArrayRequest(localURL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response){
try{
for (int i=0; i < response.length(); i++)
{
JSONObject jsonObject = response.getJSONObject(i);
String title = jsonObject.getString("Beschreibung");
String addres = jsonObject.getString("Adresse");
String laengen = jsonObject.getString("Longitude");
String breiten = jsonObject.getString("Latitude");
data += "Lagerstandort "+(i+1)+"\nBeschreibung: "+title+"\nAdresse: "+addres+"\nLängengrad: "+laengen+"\nBreitengrad: "+breiten+"\n\n\n";
}
output.setText(data);
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error){
Toast.makeText(MainActivity.this, "No more Items Available", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(localJReq);
所有这一切都发生在onCreate()
内
当然输出是我的TextView output = (TextView) findViewById(R.id.jsonData);
- 它已经在我重建的教程中工作了,所以它应该不是问题。
当我运行我的应用程序时,我得到onErrorResponse,抛出Toast消息Toast.makeText(MainActivity.this, "No more Items Available", Toast.LENGTH_LONG).show();
我的REST API启动并运行100%,所以它也不应该是一个问题。
我的sdk设置和依赖项是
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.b101.closestapp"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile project(':volley')
}
我的猜测是我的JSONArrayRequest做得不对吗?但我不确定..
谢谢