spinner list is not displaying in android - android

Hi in the below code fetching all the building details from API's .After getting the response from the server and then I am adding to the spinner.
In the below code want to display names of the building want to display in spinner.
below response want to display all the names in spinner list.
can any one help me where I did the mistake.
Response from server:
{
"list": [
{
"ID": "6",
"Name": "Microsoft1"
},
{
"ID": "9",
"Name": "building6567"
}
]
}
private void selectBuilding() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
progressDialog = new ProgressDialog (getActivity ());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Communicating...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client (client)
.build();
API service = retrofit.create (API.class);
final Call<Managebuilding> userCall = service.getbuildinglist ();
userCall.enqueue(new Callback<Managebuilding> () {
#Override
public void onResponse(Call <Managebuilding> call, Response <Managebuilding> response) {
if (response != null && response.code ( ) == 200 && response.isSuccessful ( )) {
Managebuilding building = response.body ();
arrayList = new ArrayList <> ( );
arrayList.addAll(building.getList());
adapter = new ArrayAdapter<String>(getContext (), android.R.layout.simple_spinner_item, building.getList());///error
spinner.setAdapter(adapter);
/** Adding radio buttons for the spinner items */
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
progressDialog.dismiss ( );
} else {
progressDialog.dismiss ( );
Log.d ("Response errorBody", String.valueOf (response.errorBody ( )));
}
}
#Override
public void onFailure(Call<Managebuilding> call, Throwable t) {
// lv.setAdapter (adapter);
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
progressDialog.dismiss();
Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
// progressDialog.dismiss();
}
});
}
}, 5000);
return ;
}

Create a pojo class
public class SpinnerUtils {
public SpinnerUtils(String spinnerText, int value) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public int getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
int value;
}
Then
SpinnerUtils items[]=new SpinnerUtils[array.length()];
items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));
for (int i = 0; i <array.length(); i++) {
items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));
}
ArrayAdapter<SpinnerUtils> adapter = new ArrayAdapter<SpinnerUtils>(this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
where s is your spinner and array is the JSONArray retrieved from API. To retrieve the id:
SpinnerUtils d = items[position];
int standard = d.getValue();
Create the above 2 lines within the setOnItemSelectedListener of the spinner to get the id.Hope it will work.

Related

how to output data from xampp to Textview

the code below I have successfully displayed the data but using the recyclerView. I want to ask how to display data if using Textview?
private void loadDataMahasiswa() {
progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Loading ...");
progress.show();
String nip = editTxtnip.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI api = retrofit.create(LoginAPI.class);
Call<Value> call = api.view3(nip);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
}
});
}
the results of the variables above are not readable sir
<?php
require_once('dbConnect.php');
date_default_timezone_set("Asia/Jakarta");
$timestamp = date('Y-m-d');
if($_SERVER['REQUEST_METHOD']=='GET')
$opd = $_GET['opd'];{
$sql = "SELECT COUNT(*)FROM(SELECT DISTINCT waktu,status from absen_pagi where opd='$opd' AND waktu='$timestamp')as dt";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array('waktu'=>$row['COUNT(*)']));
}
echo json_encode(array("value"=>1,"result"=>$result));
mysqli_close($con);
}
this my php json
If you are not using ArrayList of data then just add this line inside the response body
See below code
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
String myData = response.body().toString(); // convert data to string
textView.setText(myData); // just add data to textView
}
}
Let me know if not solved yet

How to return or use list as a response of multiple requests using retrofit2/rxjava2?

I need a list of articles as a response that I set in my adapter. When the code is like below, nothing happens. The program does not go in place 1. or 2.
On the other hand, when I uncomment the line that makes the method adynchronous, I have correct response, at 1. place and 2. place, I can display the list of responses. However, I can't do anything with it, neither copy nor return nor set in adapter there.
What can I do to get a list of articles? Help please :(
Here is the interface:
#GET("articles/{id}")
Observable<Articles> getArticle1(#Path("id") int id);
and here is the function:
private void getListArticles(List<Integer> l) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
final List<Articles> ar = new ArrayList<>();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
List<Observable<?>> requests = new ArrayList<>();
for(int id: l){
requests.add(apiInterface.getArticle1(id));
}
Observable.zip(requests, new Function<Object[], List<Articles>>() {
#Override
public List<Articles> apply(#NonNull Object[] objects) throws Exception {
// PLACE 1.
List<Articles> articlesArrayList = new ArrayList<>();
for (Object response : objects) {
articlesArrayList.add((Articles) response);
}
System.out.println(articlesArrayList );
System.out.println("hello");
return articlesArrayList;
}
})
//.subscribeOn(Schedulers.io()) //async
.observeOn(Schedulers.newThread())
.subscribe(
new Consumer<List<Articles>>() {
#Override
public void accept(List<Articles> articlesList) throws Exception {
// PLACE 2.
ar.addAll(articlesList);
// set adapter
//recycleView.setAdapter(new Adapter (articlesList, getApplicationContext ()));
System.out.println(articlesArrayList );
System.out.println("hello");
}
},
new Consumer<Throwable>() {
#Override
public void accept(Throwable e) throws Exception {
}
}
);
System.out.println(ar);
//return ar;
}

How to Fetch Dynamically generated report from Server in android Using Retrofit?

There are answers to this questions maybe but none of them helped me still getting the same error .
Actually trying to get dynamically generated report in android from server using retrofit .
But I am getting error while returning response .
ERROR : onFailure:: Failed java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line
1 column 1 path $
Please , I need help .
My Jason
{
"LoanDetails": [
{
"SrNo": "1",
"LoanId": "BN582517",
"StaffName": "Some Name",
"Gender": "Male",
"DisbursementDate": "2019-09-11",
"RecoveryDate": "2019-10-11",
"NameOfBorrower": "Muhammad Hassan Magsi",
"GuardianName": "Allah Dino",
"NICNumber": "Some CNIC",
"RegionName": "Some Name",
"LoanAmountPrincipal": "100000",
"InterestRate": "22",
"LoanTerm": "12",
"TotalLoanAmount": "123000.0000",
"TotalRecoveredAmount": "0",
"Balance": "Balance",
"LastPaymentDate": "--",
"DueInstallment": "0",
"OverDues": "0",
"TotalDues": "0",
"PrePayment": "0",
"ReceiptNo": "3124",
"AmountRecovered": "",
"RemainingDues": "",
"Date": "2019-09-11"
}
]
}
My Interface .
public interface ApiInterface {
#GET("employees/tabData/tablet_reports.php")
Call < ServerResponseParser > getReport();
}
Retrofit Client .
public class ApiClient {
public static final String BASE_URL = "http://mmsold.safcosupport.org/";
public static Retrofit retrofit = null;
public static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.MINUTES)
.connectTimeout(5, TimeUnit.MINUTES)
.build();
public static Retrofit getClient() {
if (retrofit == null) {
Gson gson = new GsonBuilder ()
.setLenient()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory( GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
POJO Class .
public class LoanDetail {
#SerializedName("SrNo")
#Expose
private String srNo;
#SerializedName("LoanId")
#Expose
private String loanId;
}
Just sample provide complete class if needed .
ServerResponseParser Class
public class ServerResponseParser implements Serializable {
#SerializedName("LoanDetails")
#Expose
private ArrayList <LoanDetail> loanDetails = new ArrayList <LoanDetail>( );
public ArrayList < LoanDetail > getLoanDetails () {
return loanDetails;
}
public void setLoanDetails ( ArrayList < LoanDetail > loanDetails ) {
this.loanDetails = loanDetails;
}
}
Code in MainActivity
public void getReport(){
progressDialog = new ProgressDialog (MainActivity.this);
progressDialog.setMessage("Fetching Data...");
progressDialog.setCancelable(false);
progressDialog.show();
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<ServerResponseParser> call = apiService.getReport ();
call.enqueue ( new Callback < ServerResponseParser > () {
#Override
public void onResponse ( Call < ServerResponseParser > call , Response < ServerResponseParser > response ) {
if (response.isSuccessful ()){
ArrayList<LoanDetail> statioList = response.body().getLoanDetails ();
Log.e ( "onResponse: " , statioList.toString () + "" );
}else {
Log.e ( "onResponse: " , "Empty Response" + response.body ().toString () );
}
progressDialog.dismiss ();
}
#Override
public void onFailure ( Call < ServerResponseParser > call , Throwable t ) {
Log.e ( "onFailure: " , "Failed " + t.getMessage () );
progressDialog.dismiss ();
}
} );
}

how to fetch limited data using api in retrofit

Im able to fetch data using retrofit in android and able to set it view in recyclerView using adapter.but the thing is i don't want to fetch whole data from my api i want to remove some data from my api using java which should not be visible in recyclerview.
Android studio, java
private void getSearchProduct(String str_search_text, String page_no, String limit, final String catid) {
final ProgressDialog progressDialog = new ProgressDialog (this);
if (limit.equalsIgnoreCase ("")) {
progressDialog.show ();
progressDialog.setMessage ("Please wait...");
progressDialog.setCancelable (false);
} else {
progressDialog.setMessage ("Please wait...");
progressDialog.setCancelable (false);
}
if (page_no.equalsIgnoreCase ("")) {
pagenonew = "";
} else {
pagenonew = page_no;
}
Log.e (TAG, "getSearchProduct: catid..............." + catid);
if (catid.equals ("")) {
category_id = catid;
Log.e (TAG, "getSearchProduct: catid" + catid);
}
apiService = ApiUtils.getAPIService ();
apiService.getSearchProduct ("" + latitude, "" + longitude, CustomerID, str_search_text, pagenonew, catid).enqueue (new Callback<Search_Product_Model> () {
#Override
public void onResponse(Call<Search_Product_Model> call, Response<Search_Product_Model> response) {
if (response.isSuccessful ()) {
int status = response.body ().getStatus ();
String meg = response.body ().getMsg ();
if (status == 1) {
serach_product_lists.clear ();
serach_product_lists = response.body ().getProductList ();
/* categoryID = response.body ().getCategory_id ();
Log.e (TAG, "categoryID: categoryID......" + categoryID);*/
Search_Product_Adapter adapter = new Search_Product_Adapter (SearchProduct_Fragment.this, serach_product_lists);
recycler_views_category_offerzone.setAdapter (adapter);
txt_noproduct.setVisibility (View.GONE);
recycler_views_category_offerzone.setVisibility (View.VISIBLE);
} else {
txt_noproduct.setVisibility (View.VISIBLE);
txt_noproduct.setText (meg);
recycler_views_category_offerzone.setVisibility (View.GONE);
}
progressDialog.dismiss ();
} else {
progressDialog.dismiss ();
}
}
#Override
public void onFailure(Call<Search_Product_Model> call, Throwable t){
progressDialog.dismiss ();
}
});
}
I think you should use RxJava in combination with Retrofit (they really work amazingly togheter) that has operator take which allows you to choose how many result to take
Observable.just(1, 2, 3, 4, 5, 6, 7, 8)
.take(4)
.subscribe(new Subscriber<Integer>() {
#Override
public void onNext(Integer item) {
System.out.println("Next: " + item);
}
#Override
public void onError(Throwable error) {
System.err.println("Error: " + error.getMessage());
}
#Override
public void onCompleted() {
System.out.println("Sequence complete.");
}
});
for more documentation please look at http://reactivex.io/documentation/operators/take.html
for combining Retrofit and RxJAva
https://www.journaldev.com/20433/android-rxjava-retrofit
Ask your service provider don't return the data you don't want to fetch.
Traverse your data list to find the data you don't want then remove them .As the following codes!
serach_product_lists = response.body ().getProductList ();
for(data:serach_product_lists){
if(//put your judge code here)
serach_product_lists.remove(data)
}

How to fetch Data of List<Sting> as in global Variable to get data in Oncreate() Method?

PostData.java
public class PostData {
List<String> gobalAr=new ArrayList<String>();
public List<String> getList(){
return gobalAr;
}
public void setList( List<String> gl){
this.gobalAr = gl;
}
String url = "http://btownmedia.com/";
ArrayList<Post> postArry = new ArrayList();
public List<String> bankin = new ArrayList<String>();
public void getRetrofitPostHospitalObject() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitObjectAPI service = retrofit.create(RetrofitObjectAPI.class);
Call<PostArtical> call = service.getPostHospitalDetails();
call.enqueue(new Callback<PostArtical>() {
#Override
public void onResponse(Response<PostArtical> response, Retrofit retrofit) {
try {
List<Post> PostData = response.body().getPosts();
for (int i = 0; i < PostData.size(); i++) {
Post p = new Post();
p.setId(PostData.get(i).getId());
p.setTitle(PostData.get(i).getTitle());
p.setExcerpt(PostData.get(i).getExcerpt());
p.setThumbnail(PostData.get(i).getThumbnail());
postArry.add(p);
}
gobalAr=new ArrayList<String>();
for (int i = 0; i < postArry.size(); i++) {
Post c = new Post();
c=postArry.get(i);
gobalAr.add(c.getTitle());
}
setList(gobalAr);
Log.d("valuein",gobalAr.toString()); //[Birtamode Eye Hospital (P) Ltd., Birta City Hospital, Life Line Hospital]
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
Log.d("valueout",gobalAr.toString()); // null
}}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PostData postData = new PostData();
postData.getRetrofitPostHospitalObject();
List<String> list = postData.getList();
Log.d("On", list.toString()); //null
}}
When I am Trying to access Data which From PostData class of method getRetrofitPostHospitalObject() variable "List gobalAr " in MainActivity when i call it is showing null value in gobalAr, Where as I have insert Data from of gobalArr in which add getRetrofitPostHospitalObject(), Please can Help..
Actually i want to access data "gobalAr" variable of PostData class to an MainActivity.
create get() method for List,like this
public List<String> getList(){
return *****;
}
Easy solution call this method in MainActivity
public void getRetrofitPostHospitalObject() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitObjectAPI service = retrofit.create(RetrofitObjectAPI.class);
Call<PostArtical> call = service.getPostHospitalDetails();
call.enqueue(new Callback<PostArtical>() {
#Override
public void onResponse(Response<PostArtical> response, Retrofit retrofit) {
try {
List<Post> PostData = response.body().getPosts();
for (int i = 0; i < PostData.size(); i++) {
Post p = new Post();
p.setId(PostData.get(i).getId());
p.setTitle(PostData.get(i).getTitle());
p.setExcerpt(PostData.get(i).getExcerpt());
p.setThumbnail(PostData.get(i).getThumbnail());
postArry.add(p);
}
gobalAr=new ArrayList<String>();
for (int i = 0; i < postArry.size(); i++) {
Post c = new Post();
c=postArry.get(i);
gobalAr.add(c.getTitle());
}
setList(gobalAr);
Log.d("valuein",gobalAr.toString()); //[Birtamode Eye Hospital (P) Ltd., Birta City Hospital, Life Line Hospital]
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
Log.d("valueout",gobalAr.toString()); // null
}
Then do the rest inside. problem solved

Categories

Resources