使用Retrofit填充数组适配器

时间:2014-12-25 02:25:24

标签: android android-listview retrofit

我是Android开发的新手,今天刚刚发现了Retrofit。我希望构建一个消耗我网站API的Android应用程序,看起来Retrofit很适合这个账单。

我正在尝试使用我的API中以JSON形式返回的数据填充ListView,但无法弄清楚我需要做什么。我已经在我的代码中直接使用虚拟数据填充了ListView(对不起,很多代码):

public class MainActivity extends ActionBarActivity {
    public static final String TAG = "App";
    public static ListView mListView;
    private List<User> users = new ArrayList<User>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView)findViewById(R.id.usersListView);


        populateUserList(); // Add items to the Users array
        populateListView(); // Add the Users to the List View
    }

    // Add items to the User List array
    // This is what I want to populate from my API
    private void populateUserList() {
        users.add(new User("Joe Smith", "jsmith@nowhere.com"));
        users.add(new User("Frank Smith", "fsmith@somewhere.net"));
        users.add(new User("Mary Jane", "mjane@website.org"));
    }

    //Add the Users Array to the List View
    private void populateListView() {
        ArrayAdapter<User> adapter = new UserListAdapter();
        mListView.setAdapter(adapter);

    }

    private class UserListAdapter extends ArrayAdapter<User> {
        public UserListAdapter(){
            super(MainActivity.this, R.layout.user_item, users);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            // Check if Item View is null
            if (itemView == null)
            {
                // Need to create a new view - make sure we have a view to work with.
                itemView = getLayoutInflater().inflate(R.layout.user_item, parent, false);
            }

            // Find the user to work with
            User currentUser = users.get(position);

            // Fill the view
            TextView nameField = (TextView)itemView.findViewById(R.id.list_nameField);
            TextView emailField = (TextView)itemView.findViewById(R.id.list_emailView);

            nameField.setText(currentUser.getName());
            emailField.setText(currentUser.getEmail());

            return itemView;
        }
    }

以下是我的Retrofit API代码:

public interface Api {
    @GET("/httplist")
    List<User> userList();
}

..和我的Rest客户:

public class RestClient {

    private static Api REST_CLIENT;
    private static String ROOT = "https://somewhere.org";
    static {
        setupRestClient();
    }
    private RestClient() {}
    public static Api get() {
        return REST_CLIENT;
    }

    private static void setupRestClient() {
        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(ROOT)
                .setClient(new OkClient(new OkHttpClient()))
                .setLogLevel(RestAdapter.LogLevel.FULL);
        RestAdapter restAdapter = builder.build();
        REST_CLIENT = restAdapter.create(Api.class);
    }
}

..用户类..

public class User {
        private String name;
        private String email;

        public User(String name, String email) {
            super();
            this.name = name;
            this.email = email;
        }

        public String getName() {
            return name;
        }

        public String getEmail() {
            return email;
        }
    }

最后,我试图处理一些简单的JSON:

[
{"name":"John Smith","email":"jsmith@somewhere.net"}
...
]

我觉得我很接近,但我似乎无法将其连接起来。非常感谢帮助!感谢。

更新 先这样做。我不得不将API请求放在Runnable中以避免NetworkOnMainThread异常。这些物品没有被添加。

private void populateUserList() {
        users.add(new User("Joe Smith", "jsmith@nowhere.com"));
        users.add(new User("Frank Smith", "fsmith@somewhere.net"));
        users.add(new User("Mary Jane", "mjane@website.org"));
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    users = RestClient.get().userList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

1 个答案:

答案 0 :(得分:3)

您可以使用由Retrofit提供的REST方法的异步版本。这使您无需为网络操作创建单独的后台线程,并使代码更清晰。获得用户列表后,请更新适配器。您不需要单独的用户阵列。

private void populateUserList() {
  RestClient.get().userList(new Callback<List<User>>() {
    public void success(List<User> users, Response response) {
      // this is called in main thread so it's ok to update views
      mUsersAdapter.clear();
      mUsersAdapter.addAll(users);
    } 
    public void failure(RetrofitError error) {
      // handle error
    }
  });
}