How to fetch information from server and assign that data to Spinner
using retrofit and Gson
converter?
Gradle
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
}
PhP code
<?php
require "con.php";
$sql = "SELECT * FROM Tbl_cross";
$result = mysqli_query($con,$sql);
$response = array();
while ($row = mysqli_fetch_array($result))
{
array_push($response,array('cross'=>$row['school_cross']));
}
echo json_encode ($response);
mysqli_close($con);
?>
XML code
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout
android:background="#d0d0f7"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:id="@+id/spinner"
android:layout_width="368dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.015" />
</android.support.constraint.ConstraintLayout>
1.Firstly get data from the response, which you want to set in spinner. For example, show the list of dates.
private ArrayList<String> datesList=new ArrayList<>();
datesList.addAll(response.body().getData());
setDatesSpinner();
2.Call setDatesSpinner
method for setting data in spinner.
private void setDatesSpinner() {
ArrayAdapter<String> datesAdapter = new ArrayAdapter<String>(this, R.layout.item_progress_date_list, datesList);
pro_date_spinner.setAdapter(datesAdapter);
pro_date_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.