Retrofit Equeue Multiple RecyclerViews - java

I am using retrofit2 to enqueue multiple recyclerviews. It works great on one recyclerview but when i go to enqueue a second one with a different category it doesnt work.
I have tried making a second onresponse method, i cant think of any other way of doing it
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);//This one is working!
Call<MovieResponse> call1 = apiInterface.getNowPlayingMovies(API_KEY); //This is what i what to implement
Here is the code
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext())); //this works but not with the NowPlayingMovies, tested to see if it was the other recyclerview
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});

If you dont prefer to use RxJava then you can use following solution:
Call<MovieResponse> call = apiInterface.getTopRatedMovies(API_KEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
secondAPICall();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
public void secondAPICall(){
call1.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
int statuscode =response.code();
List<Movie> movies = response.body().getResults();
recyclerView1.setAdapter(new MoviesAdapter(movies, R.layout.movie_item, getContext()));
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

Related

Populate spinner upon clicking it

I am trying out this simple program where I try to send a POST request to the server and fetch the response and store them into the spinner. This is my code;
fetchcolonynames("code"); //sending POST request
if (spin1 != null) {
//spin.setAdapter(adapter) doesn't work here
spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spin1.setAdapter(adapter); //doesn't work spinner shows nothing on clicked
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
This is my fetchcolonynames() method:
private void fetchcolonynames(String input){
call=api.fetchcolonynames(input);
if(call!=null){
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.body() != null) {
JSONArray array = null;
try {
array = new JSONArray(response.body());
for(int i=0;i<array.length();i++){
arr.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Collections.sort(arr); //data is correct here
adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item,arr);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
}
All my variables are globally declared. I want to populate the spinner, when the user clicks it. How do I accomplish this?

SwipeRefresh layout progress bar is not hiding even after completion

I am using MVVM pattern in which I am using SwipeRefresh layout to refresh recycler view in my layout.When I am pulling it then it continue to refresh even after method completed successfully.
Below is my code:
MainActivity.java
refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
userRepository.getUserList();
}
});
UserRepository.java
public void getUserList(){
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<User>> userList = apiService.getUser();
userList.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, final Response<List<User>> response) {
Completable.fromAction(new Action() {
#Override
public void run() throws Exception {
if(response.body() != null) {
List<User> list = response.body();
for (int i = 0; i < list.size(); i++) {
String id = list.get(i).get_id();
String names = list.get(i).getName();
String age = list.get(i).getAge();
User user = new User(id,names,age);
userDb.userDao().Insert(user);
}
}
}
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new CompletableObserver() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onComplete() {
Toast.makeText(context,"Data inserted",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(context,e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(context,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
Method fetching list is in another class UserRepository and I am calling method in another activity MainActivity.I am not getting any way how can I stop refreshing process.Someone please let me know a way to stop refreshing process.
Any help would be appreciated.
THANKS
To disable the progress dialog add this,
swipeLayout.setRefreshing(false);

How to set dynamically model class to Retrofit requests?

In my application i want use Retrofit2 library for requests and i want set dynamically response model, i don't want set model into interface model!
For example :
My interface method is :
#GET("api/server?mode=supports")
Call<SupportListResponse> getSupport_List(#Header("jwt") String token);
I don't want set SupportListResponse into Call<> , i want set this model dynamically from Activity/Fragment class!
How can i set general model class instead of SupportListResponse ?
My activity full code :
public class TimerRecyclerActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ProgressBar timerProgressBar;
private List<Today> model = new ArrayList<>();
private Adapter adapter;
private ApiInterface api;
private LinearLayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_recycler);
api = ApiClient.getClient().create(ApiInterface.class);
adapter = new Adapter(getApplicationContext(), model);
adapter.setHasStableIds(true);
recyclerView = findViewById(R.id.timerRecyclerView);
timerProgressBar = findViewById(R.id.timerProgressBar);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
Call<AuctionsListResponse> call = api.getMainAuctions("", 1, 10);
call.enqueue(new Callback<AuctionsListResponse>() {
#Override
public void onResponse(Call<AuctionsListResponse> call, Response<AuctionsListResponse> response) {
if (response.isSuccessful()) {
if (response.body().getRes() != null) {
if (response.body().getRes().getToday().size() > 0) {
timerProgressBar.setVisibility(View.GONE);
model.clear();
model.addAll(response.body().getRes().getToday());
adapter.notifyDataSetChanged();
}
}
}
}
#Override
public void onFailure(Call<AuctionsListResponse> call, Throwable t) {
}
});
}
}
How can i it?
Do Some modification in your code
#GET("api/server?mode=supports")
Call<ResponseBody> getSupport_List(#Header("jwt") String token);
while getting retrofit object
public static Retrofit getWorkbook() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
}
return retrofit;
}
in main Activity Retrofit
private void gettingResponseFromRetrofit() {
ApiInterface api = ApiClient.getWhatsNew().create(ApiInterface.class);
Call<ResponseBody> call = api.getSupport_List("", 1, 10);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
// here you will get the response
// do your stuff
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Some Error Occur", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}

Reply from Retrofit

I'm making a GET request:
public interface CheckUserInDBRequest {
#GET("api/checkUserInDB.php")
Call<ResponseBody> searchForUser(
#Query("login") String login,
#Query("pass") String pass
);
}
And I get the answer true || false in json, according to whether there is a user in the database or not.
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://kurusa.zhecky.net/").addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
CheckUserInDBRequest client = retrofit.create(CheckUserInDBRequest.class);
Call<ResponseBody> call = client.searchForUser (
UserLogin.getText().toString(),
UserPass.getText().toString()
);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "no ", Toast.LENGTH_SHORT).show();
}
});
Here is just the output of okHttp3. I do not understand how to get a normal answer.
First, create a class representing your JSON object
public class UserResult {
public boolean isSet;
}
Restructure your Retrofit call in this way
#GET("api/checkUserInDB.php")
Call<UserResult> searchForUser(
#Query("login") String login,
#Query("pass") String pass
);
Then in your code:
call.enqueue(new Callback<UserResult>() {
#Override
public void onResponse(#NonNull Call<UserResult> call, #NonNull Response<UserResult> response) {
if (response.isSuccesfull()) {
UserResult result = response.body();
//use the value result.isSet where you need it
} else {
//something is broken
}
}
#Override
public void onFailure(#NonNull Call<UserResult> call, #NonNull Throwable t) {
Toast.makeText(MainActivity.this, "no ", Toast.LENGTH_SHORT).show();
}
});

Retrofit, TimeoutException

I'm using retrofit authentication, and I have a timeoutexception. I saw many questions, but I can't solve this.
Here's the code
public class FragmentRegistration extends Fragment {
View mainView;
EditText username, email, password, name;
Button button;
ApiClient pentairAPIClient = ApiClient.getInstance();
SupportopObj supportopObj = new SupportopObj();
SupportopObjActivate supportopObjActivate = new SupportopObjActivate();
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate
(R.layout.registration, container, false);
username = mainView.findViewById(R.id.username);
email = mainView.findViewById(R.id.email);
password = mainView.findViewById(R.id.password);
name = mainView.findViewById(R.id.name);
button = mainView.findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String s = name.getText().toString();
//String split[] = s.split(" ");
supportopObj.setFirstName("Tester");
supportopObj.setLastName("Testryan");
supportopObj.setUsername(username.getText().toString());
supportopObj.setEmail(email.getText().toString());
supportopObj.setPassword(password.getText().toString());
supportopObjActivate.setUsername(supportopObj.getUsername());
supportopObjActivate.setEmail(supportopObj.getEmail());
supportopObjActivate.setPassword(supportopObj.getPassword());
supportopObjActivate.setType("generic");
updateApp();
}
});
return mainView;
}
public void updateApp() {
Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
activationCall();
} else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
}
});
}
public void activationCall() {
Call<ResponseBody> callActive = pentairAPIClient.activation(supportopObjActivate);
callActive.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String data = response.body().string();
JSONObject obj = new JSONObject(data);
String client_id = obj.getString("client_id");
String client_secret = obj.getString("client_secret");
tokenCall(client_id, client_secret);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error in activation",
Toast.LENGTH_SHORT).show();
}
});
}
public void tokenCall(String client_id, String client_secret) {
Call<ResponseBody> token = pentairAPIClient.get_token("password", client_id, client_secret,
supportopObj.getEmail(), supportopObj.getPassword());
token.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something wrong.....", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "You're on failure", Toast.LENGTH_SHORT).show();
}
});
}
}
I have no error in retrofit, I'm doing debugging and I see all the process, so I getting client id and secret successfully, then I'm getting a timeoutexception in the last onfailure(),
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
Toast.makeText(getContext(), "You're onfailure",Toast.LENGTH_SHORT).show();
}
watch the code, that's the last line. How to fix it? The app not crashes, but in debug he drops timeoutexception like this. t={SocketTimeoutException#830038722120}java.net.SocketTimeoutException: timeout . In OkHttpClient the
readTimeout(10, TimeUnit.SECONDS).connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS); all are 10, i tried to set it 100, not helps. Help me. Thanks.

Categories