我是Android Studio的新手,想为Android Studio创建Lumen API,我创建了一个简单的Android项目,从lumen web.php文件中获取数组项列表,并将其显示为xml listview。
我工作得很好。
我的问题是,我创建了一个简单的LaravelLumenAPI,在该API中,当URL被点击时,它会转到Lumen项目的web.php,并用一个数组返回json响应。
我的web.php文件如下:
$router->get('/demo',function(){
$array = User::get();//variable array contain all users data
return response()->json($array);
});
我的主要活动如下:
package com.example.ram.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewHeroes);
//calling the method to display the heroes
getHeroes();
}
private void getHeroes() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
Api api = retrofit.create(Api.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
List<Hero> heroList = response.body();
//Creating an String array for the ListView
String[] heroes = new String[heroList.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < heroList.size(); i++) {
heroes[i] = heroList.get(i).getName();
}
//displaying the string array into listview
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, heroes));
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
我希望在XML列表视图中显示此数组,但它在Emulator上显示的错误为:
“应为begin_数组,但在第1行第2列路径$处为begin_对象。”
请帮助我如何使用Android Studio处理JSON响应