B
B
Brenly2021-02-15 09:59:16
Android
Brenly, 2021-02-15 09:59:16

How to fill Spiner with data from Web service using tasks?

Task.
You need to get a list of users from the web service and transfer it to the spinner.

spoiler
public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spiner = findViewById(R.id.spiner);

        AsyncTaskRunner task = new AsyncTaskRunner(spiner,getApplicationContext());
        task.execute();
    }
}

class ListUser {

    @SerializedName("User")
    @Expose
    private String user;
    @SerializedName("Uid")
    @Expose
    private String uid;

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

}

// ...

// ...

class AsyncTaskRunner extends AsyncTask<Void, Void, List<ListUser>> {
    Spinner spinner;
    Context context;

    public AsyncTaskRunner(Spinner spinner, Context context){
        this.spinner = spinner;
        this.context = context;
    }

    @Override
    protected List<ListUser> doInBackground(Void... params) {

        List<Header> headers = new ArrayList<>();
        ApiService api = new Api(headers);
        headers.add(new AuthHeader("http", "http"));
        List<ListUser> users = api.getUsers();
        return users;
    }

    @Override
    protected void onPostExecute(List<ListUser> result) {
        final List<ListUser> users = result;

        ArrayAdapter<ListUser> adapter = new ArrayAdapter<>(context,R.layout.row,R.id.textRow, users);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(context,users.get(position).getUser(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}


The spinner does not display the username, but a link. The adapter parameter accepts a List as it should.
602a1b60ccdaf614372693.png
And when you try to open the list - an error falls
602a1bb0cdef8405237066.png

I ask for help how to win?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Brenli, 2021-02-15
@Brenli

I solved the problem by overriding ListUser's toString() method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question