How to show response.body form from retrofit in a spinner
After the response is fully done you should be able to set the adapter with the new items.
@Override
public void onResponse(Call<List<Plant>> call, Response<List<Plant>> response) {
for (Plant p : response.body()) {
plantasInvasorasNombre.add(p.getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(context,android.R.layout.simple_spinner_item,plantasInvasorasNombre);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
How to retrieve 2 values using retrofit with spinner
Don't provide i-1
. Your index also start from 0 but when you try to select baru it takes position 0 - 1 = -1
. So just provide i which is index of baru in ArrayList.
spinnerProvinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int IDProvinces = getProvincesIDList.get(i);
Toast.makeText(getContext(), "ID Province : " + IDProvinces, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Dynamically populating spinner using Retrofit?
first create theretrofitapi interface
/**
* reCreated by goodlife on 1/11/2016.
*/
import java.util.List;
import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
/**
* Created by Belal on 11/5/2015.
*/
public interface RetrofitInternetApi {
//@FormUrlEncoded, we have to write this if we want to send post data to the server.
//@POST, because we are using an HTTP Post request we have written this.
// Inside it we have the URL of the script that will be receiving the post request.
// Note that the URL is excluding the root URL. And we have defined the root URL in our MainActivity.
//@Field(“key”) String variable inside key we have to write what we have written inside $_POST[‘key’] in our script.
// And we have to specify it for all the values we are going to send.
//Callback<Response> callback it is also inside the retrofit library. It will receive the output from the server.
//But this is only an interface and the method is abstract.
//We will define the method inside fetchDepartmentName() method that is declared inside MainActivity.java.
@GET("/getDepartmentName.php")
public void getDepartmentName(Callback<List<DepartmentNoRealm>> response);
}
then create the function
private void fetchDepartmentName(){
//Creating a rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL)
.build();
//Creating an object of our api interface
RetrofitInternetApi retrofitInternetApi = restAdapter.create(RetrofitInternetApi.class);
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Fetching Data", "Please wait...", false, false);
//Defining the method
retrofitInternetApi.getDepartmentName(new Callback<List<DepartmentNoRealm>>() {
@Override
public void success(List<DepartmentNoRealm> list, Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.d("JSON LIST",list.toString());
//Storing the data in our list
departmentNoRealmList = list;
//Calling a method to show the list
showListinSpinner(); }
@Override
public void failure(RetrofitError error) {
//you can handle the errors here
}
});
}
then create a class model
package myafya.safaricom.co.ke.myafya.model.realm;
/**
* Created by 001557 on 1/13/2016.
*/
public class DepartmentNoRealm {
public int departmentID;
public String departmentName;
public String departmentURLimage;
public int getDepartmentID() {
return departmentID;
}
public void setDepartmentID(int departmentID) {
this.departmentID = departmentID;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentURLimage() {
return departmentURLimage;
}
public void setDepartmentURLimage(String departmentURLimage) {
this.departmentURLimage = departmentURLimage;
}
}
now the code showList in Spinner
//Our method to show list
private void showListinSpinner(){
//String array to store all the book names
String[] items = new String[departmentNoRealmList.size()];
//Traversing through the whole list to get all the names
for(int i=0; i<departmentNoRealmList.size(); i++){
//Storing names to string array
items[i] = departmentNoRealmList.get(i).getDepartmentName();
}
//Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
//setting adapter to spinner
spinnerDepartments.setAdapter(adapter);
//Creating an array adapter for list view
}
Then SHARE IT AND MAKE IT EASY
MY JSON WAS
[
{
"departmentID": "1",
"departmentName": "Enterprise Business Unit (EBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcSKOZmGNAA08NbHwRJrloAouWqs6r4x7BGXY4k-ULWiHuPEobHI"
},
{
"departmentID": "2",
"departmentName": "Consumer Business Unit (CBU)",
"departmentURLimage": "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ0IAFhZ52KiG_0ck5VbBxweZWf_MEA9eRmgHAEr6CG-rUG_a2QEQ"
}
]
How to Retrieve 2 Values from Spinner with Retrofit2 on Android
In your response :
private void initSpinnerType(){
RetrofitInterface api = RetrofitClient.getClient().create(RetrofitInterface.class);
Call<LeaveTypeResponse> call = api.getDataPermit();
call.enqueue(new Callback<LeaveTypeResponse>() {
@Override
public void onResponse(Call<LeaveTypeResponse> call, Response<LeaveTypeResponse> response) {
if (response.isSuccessful()) {
List<LeaveType> leaveTypeItems = response.body().getResult();
for (int i = 0; i < leaveTypeItems.size(); i++){
String Code = leaveTypeItems.get(i).getCode(); // I want to show this when Selected
String leaveType = leaveTypeItems.get(i).getType();
listSpinner.add(leaveType);
// Add your code into an separate ArrayList
listCode.add(code);
}
listSpinner.add(0, "- SELECT TYPE -");
adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, listSpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
leaveType.setAdapter(adapter);
} else {
Toast.makeText(context, "FAILED", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<LeaveTypeResponse> call, Throwable t) {
t.printStackTrace();
Toast.makeText(context, "CAN'T CONNECT", Toast.LENGTH_SHORT).show();
}
});
}
Your Listener :
leaveType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// position -1 because in listspinner we add an extra String at 0 index
String selectedCode=listCode.get(--position);
String selected = parent.getItemAtPosition(position).toString();
Toast.makeText(context, "Choose " + selectedCode, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Populating Spinners using Retrofit 1.9?
Below, is a sample for setting the spinner
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter;
List<String> data;
data = new ArrayList<>();
for (int i = 0; i < 20; i++)
data.add("Data " + (i + 1));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
spinner.setAdapter(adapter);
Here data is a dummy data , in your case it will be dummy data.
populate spinner with retrofit and moshi
Here is code for same, I modified and integrate in your code only:
"MainActivity.kt" class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var spinner: Spinner = findViewById(R.id.spinner)
val task = object : AsyncTask<Void, Void, Response<List<ProductTypeDataResponse>>>() {
override fun doInBackground(vararg params: Void): Response<List<ProductTypeDataResponse>> {
val typeAPI = RestAPI()
val callResponse = typeAPI.getNews()
val response = callResponse.execute()
return response
}
override fun onPostExecute(response: Response<List<ProductTypeDataResponse>>) {
if (response.isSuccessful) {
val news: List<ProductTypeDataResponse>? = response.body()
var adapter: SpinnerAdapter = SpinnerAdapter(this@MainActivity, news!!);
spinner.adapter=adapter
}
}
}.execute()
}
}
Now Layout "activity_main":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context="com.example.ankitpatidar.checkkotlin.MainActivity">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"></Spinner>
</LinearLayout>
Now Spinner Adapter as "SpinnerAdapter":
class SpinnerAdapter internal constructor(internal var context: Context, internal var list: List<ProductTypeDataResponse>) : BaseAdapter() {
override fun getCount(): Int {
return list.size
}
override fun getItem(i: Int): Any? {
return null
}
override fun getItemId(i: Int): Long {
return 0
}
override fun getView(i: Int, view: View?, viewGroup: ViewGroup): View {
var view = view
if (view == null) {
val inflater = LayoutInflater.from(context)
view = inflater.inflate(R.layout.item, viewGroup, false)
}
val textView = view!!.findViewById<TextView>(R.id.textView)
textView.text = list[i].productType + " " + list[i].readable
return textView
}
}
Spinner item layout as "item":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
</LinearLayout>
Now some changes in your existing files:
"ApiModel.kt":
class TypeDataResponse(
val children: List<ProductTypeChildrenResponse>
)
class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)
class ProductTypeDataResponse(
val productType: String,
val readable: String
)
"RestAPI.kt"
class RestAPI() {
private val tigaerApi: TigaerApi
init {
val retrofit = Retrofit.Builder()
.baseUrl("http://app.tigaer.id/laravel/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
tigaerApi = retrofit.create(TigaerApi::class.java)
}
fun getNews(): Call<List<ProductTypeDataResponse>> {
return tigaerApi.getTop()
}
}
Hence it will work for you.
Populate spinner [custom adapter] retrofit
Ok, so to implement this you need first of all to create you xml view, for example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/name_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Now in adapter in function getView()
you need to inflate it and bind the TextView
:
convertView = LayoutInflater.from(context).
inflate(R.layout.layout_list_view_row_items, parent, false);
TextView nameTextView = (TextView) convertView.findViewById(R.id.name_text_view);
//and now get the SpinnerArrayObject by position
SpinnerArrayObject currentObject = spinnerArrayObjects.get(position);
nameTextView.setText(currentObject.getName());
return convertView;
Related Topics
Android Q, Programmatically Connect to Different Wifi Ap for Internet
Showing Thumbnail for Link in Whatsapp || Og:Image Meta-Tag Doesn't Work
Android:Get Current Date and Time from Firebase
How to Edit Files Inside the Android Adb Shell
How to Get the Current Time on a Button Click
How to Execute Adb Commands Through My Android App
How to Avoid Overlap View in Relative Layout in Android
Error: Open Failed: Enoent (No Such File or Directory)
How to Remove the Black Bar Appearing At the Bottom
How to Remove Bottom Navigation View and Toolbar in Some Fragments If Using Navigation Controller
How to Change Background Color of Layout of List-View Item Using Array-Adapter
How to Restrict Entry of Numbers But Allow All the Special Characters and Alphabets in Edittext
How to Display Date Picker for Android With Only Month and Year Fields
How to Create an Android View Pager With a Dots Indicator
How to Reduce the Gap Between Tab Layout Text and Its Indicator
How to Enable Front Camera Instead of Rear Camera for Android Programmatically